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>functionsetName(el){
    document.getElementById('searchtitle').innerHTML = "Enter " + el.innerText;
}
</script></head><body><label><inputtype="radio"name="searchtype"value="name"onclick="setName(this.parentNode)"/>Last 

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

Number</label><br/><labelfor="inputfield"id="searchtitle"style="font-size:2em;">Enter Last Name</label><br/><inputtype="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).

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

JavaScript (in Jquery, for brevity):

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

Solution 4:

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

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

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

Post a Comment for "Using Innerhtml With "