简体   繁体   中英

Use of innerHTML in javascript form

I see in this example how I can change the id contents with an input button and it works fine:

Example:

<script type="text/javascript">
function changeText(){
    document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p> 
<input type='button' onclick='changeText()' value='Change Text'/>

When I try to use this to update a select or checkbox it does not work? What can I use to achieve this result with a form element?

Non-Working Example:

<script type="text/javascript">
function changeText(){
    document.getElementById('boldStuff').innerHTML = '2';
}
</script>
<p>Welcome to the site 
<input type="checkbox" id="boldStuff" value="1" /></p> 
<input type='button' onclick='changeText()' value='Change'/>

innerHTML change the HTML between the opening and closing tag. Since the input tag is a self closing tag (tag that end with /> , even though it is valid in HTML5 to leave the / behind), there is no innerHTML .

If you want to change the value, just target the value property :

document.getElementById('boldStuff').value = '2';

You should set the element's checked , not its innerHtml . Setting the innerHtml is equivalent to doing:

<input type="checkbox" id="boldStuff" value="1">2</input>

which is invalid HTML.

If you want to set the checkbox to checked, do this:

document.getElementById('boldStuff').checked = true;

If you want to set the value, set the value (and not innerHTML):

document.getElementById('boldStuff').value = '2';

Most attributes can be found in this way, tho some must be gotten from element.getAttribute and set with element.setAttribute .

to make changes via innerHTML you first need to have a innerHTML value to change

so

document.getElementById('***').innerHTML="2";

the corresponding HTML would need to look similar to this:

<p id="***">some text</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM