Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

input - HTML checkbox onclick called in Javascript

I am having a bit of trouble trying to figure out how to get a certain part of my code to work.

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" onclick="selectAll(document.wizard_form, this);">
<label for="check_all_1" onclick="toggleCheckbox('check_all_1'); return false;">Select All</label>

This is my HTML which works as it should (clicking the text will click the box). The javascript for it is pretty simple:

function toggleCheckbox(id) {
    document.getElementById(id).checked = !document.getElementById(id).checked;
}

However I want the onclick to happen for the input when the label is what makes the checkbox to be clicked. At this current time the onClick js does not go. What is one suggestion on how to do this? I tried to add the onclick of the input to the onclick of the label but that doesn't work.

Any suggestions/solutions would be wonderful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about putting the checkbox into the label, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange event?

<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....> 

function toggleCheckbox(element)
 {
   element.checked = !element.checked;
 }

This will additionally catch users using a keyboard to toggle the check box, something onclick would not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...