Skip to content Skip to sidebar Skip to footer

Using InnerHTML With

I am trying to use the innerHTML method on an input tag and all i get back is a blank string. Here is the code i am useing. javascript function setName(ID){ document.getElement

Solution 1:

you should embed input inside of label tag. input tag should closed by />. It's semantic HTML. When you do this clicking on label activate the input. InnerHTML only works for label then. It will return you label value.

<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name
    <input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />
</label>

JavaScript:

console.log(document.getElementById('searchtitle').innerHTML); // returns 'Enter Last Name'

Solution 2:

First, add labels around your inputs. Second, use getName(this.parentNode). Finally, call innerText instead of innerHtml.

<html>
<head>
<script>
function setName(el){
    document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script>
</head>
<body>
<label><input type="radio" name="searchtype" value="name" onclick="setName(this.parentNode)"/>Last 

Name</label><br/>
<label><input type="radio" name="searchtype" value="phonenumber" onclick="setName(this.parentNode)"/>Phone 

Number</label><br/>

<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label><br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;"></input>
</body>
</html>

Solution 3:


Complete edit.

Ok, I figured out what you were looking for. First off, you've got to fix your HTML (don't put text inside of an input... and don't next an input inside of a label).

<label for="test">Last Name</label>
<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)" />
<br/>
<label for="test2">Phone Number</label>
<input type="radio" id="test2" name="searchtype" value="phonenumber" onclick="setName(this)" />
<br/>
<label for="inputfield" id="searchtitle" style="font-size:2em;">Enter Last Name</label>
<br/>
<input type="text" name="inputfield" id="inputfield" style="font-size:2em;" />

JavaScript (in Jquery, for brevity):

function setName(elem)
{
    $('#searchtitle').html('Enter ' + $('label[for="'+elem.id+'"]').html());
}

Solution 4:

You have closed the Input tag improperly with </input> this should be

<input type="radio" name="searchtype" id="test" value="name" onclick="setName(this)"/>Last Name<br/>

<input type="radio" name="searchtype" value="phonenumber" onclick="setName(this)"/>Phone Number<br/>

Post a Comment for "Using InnerHTML With "