basic javascript issue
I have a webpage form with a checkbox on it. I am trying to set the box to checked clicking an that exists on another part of the webpage using the onclick.
NONE of these seem to work (form and checkbox ID/NAME are all set properly):
<a href="#" onclick="document.getElementById('frmEditBasicBasic').active.checked=TRUE;"> test </a>
<a href="#" onclick="document.frmEditBasicBasic.active.checked=TRUE;"> test </a>
<a href="#" onclick="document.getElementById('active').checked=TRUE;"> test </a>
<a href="#" onclick="window.document.getElementById('frmEditBasicBasic').active.checked=TRUE;"> test </a>
<a href="#" onclick="window.document.frmEditBasicBasic.active.checked=TRUE;"> test </a>
<a href="#" onclick="window.document.getElementById('active'开发者_如何学JAVA).checked=TRUE;"> test </a>
You should use the <label>
element instead:
<label for="active">Test</label>
Clicking this <label>
will automatically toggle the checkbox with ID active
. (If it's a textbox, it will focus the textbox)
To answer the question, TRUE
should be lowercase. (Javascript is case-sensitive)
You should use <label>
for the job:
<label for="name">Name</label>
...
<input type="checkbox" id="name" name="name" />
Or
<label><input type="checkbox" id="name" name="name" /> Name</label>
Edit
If you really want to use Javascript to do something special, you need to add return false;
to the onclick
event, to prevent the browser from changing page. Here is a Javascript example (I never use inline Javascript):
document.getElementById('somelink').onclick = function(){
document.getElementById('somecheckbox').checked = false; // Unchecks the checkbox
return false; // Prevents the browser from changing page
};
This works fine: (http://jsfiddle.net/NQ5Rm/4/)
<input type="checkbox" id="active" >
<a href="#" onclick="document.getElementById('active').checked=true;"> test </a>
JavaScript is case-sensitive, and its boolean literals are lower-case. Try obj.checked=true instead. In addition, in some browsers (e.g. Chrome) getElementById() means no more than what it says: It gets element by ID, not by name. Set the id property as well as the name property.
The following works fine for me in IE and Chrome:
<body>
<a href="#" onclick="document.getElementById('active').checked=true;"> test </a>
<form>
<input type="checkbox" name="active" id="active" value="Car" />
</form>
</body>
Some or all of your other versions will probably work equally well, if you fix the capitalization and (if you're not using IE) set id="foo" as well as name="foo" (and if you ARE using IE, bear in mind that most of us aren't).
Lastly, the <label> thing suggested by other commenters is worth knowing, and will probably solve your problem better than the JavaScript.
精彩评论