...

View Full Version : checkbox and events



ubuntu
12-26-2011, 02:27 PM
i have a checkbox:



<input type="checkbox" id="my_checkbox" name="option2" value="Check" checked>Check


i want to add an event to it so that i do something to a dom element when it is checked and when it is not checked.What is the event and how can i get its status?

jmrker
12-26-2011, 02:35 PM
Use the onclick event


// JS section
function doSomething() {
alert('Checkbox changed');
}

// HTML section
<input type="checkbox" id="my_checkbox" name="option2"
value="Check" checked onclick="doSomething()">Check

ubuntu
12-26-2011, 02:43 PM
Use the onclick event


// JS section
function doSomething() {
alert('Checkbox changed');
}

// HTML section
<input type="checkbox" id="my_checkbox" name="option2"
value="Check" checked onclick="doSomething()">Check


cheers,but how can i get if its clicked or not?
like:



// JS section
function doSomething() {
if(checked) {
alert('Checkbox is checked');
}
if (!(checked)) {
alert('not checked');
}
}

// HTML section
<input type="checkbox" id="my_checkbox" name="option2"
value="Check" checked onclick="doSomething()">Check

xelawho
12-26-2011, 03:38 PM
function doSomething() {
if(document.getElementById("my_checkbox").checked==true) {
alert('Checkbox is checked');
}
else {
alert('not checked');
}
}

ubuntu
12-26-2011, 03:51 PM
function doSomething() {
if(document.getElementById("my_checkbox").checked==true) {
alert('Checkbox is checked');
}
else {
alert('not checked');
}
}


Cheers!Thanks both!

jmrker
12-26-2011, 08:01 PM
Alternatively, you can identify multiple checkboxes, which was also not specified in original request.


<!DOC HTML>
<html>
<head>
<title> Untitled </title>
<script type="text/javascript">
function doSomething(cbox,status) {
var str = 'Checkbox '+cbox+' is '+status;
alert(str);
}
</script>
</head>
<body>

<input type="checkbox" name="option2" value="1"
onclick="doSomething(this.value,this.checked)" checked > 1
<input type="checkbox" name="option2" value="2"
onclick="doSomething(this.value,this.checked)"> 2
<input type="checkbox" name="option2" value="3"
onclick="doSomething(this.value,this.checked)"> 3
<input type="checkbox" name="option2" value="4"
onclick="doSomething(this.value,this.checked)"> 4
<input type="checkbox" name="option2" value="5"
onclick="doSomething(this.value,this.checked)" checked> 5

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum