JAVASCRIPT CHECK OUTSIDE CHECKBOXES
This tutorial and example script shows you how to add a feature to checkboxes so that they can be checked even if
users click their mouse on the text outside the checkbox. See the demo below. Click on the text outside the
checkbox to see the checkboxes get checked.
DEMO:
What type of movies do you like?
The first thing we do is create a form named demo with our checkboxes:
<form name="demo">
<input type="checkbox" name="choices" value="Romance">Romance
<input type="checkbox" name="choices" value="Horror">Horror
<input type="checkbox" name="choices" value="Action">Action
</form>
We then create a function named checkIt which will accept a variable named i as it's argument. i will reprsent the
checkbox number (first = 0, second=1, etc).
The completed function must be inserted in between the <head> and </head> section of our page.
<script type="text/javascript">
function checkIt(i)
{
We then use an if else statement to say that if a any checkbox is clicked by the user, it must be checked. If it is
clicked again, it must be unchecked (ie. clicking will toggle checked and unchecked states).
if(document.demo.choices[i].checked==true)
{
document.demo.choices[i].checked=false;
}
else
{
document.demo.choices[i].checked=true;
}
We then close the the function as below:
}
</script>
The full function script is below:
<script type="text/javascript">
function checkIt(i)
{
if(document.demo.choices[i].checked==true)
{
document.demo.choices[i].checked=false;
}
else
{
document.demo.choices[i].checked=true;
}
}
</script>
We need to add the call to action to each checkbox input tag to our form. Because we want it to check and uncheck
when a user clicks the text outside the checkbox, we enclose each checkbox input tag with a <span> tag and
also add the call to action there. See the additions (in red text) to the previous form below:
<form name="demo">
<span onclick="checkIt(0);">
<input type="checkbox" name="choices" value="Romance" onclick="checkIt(0);"
>Romance</span>
<span onclick="checkIt(1);">
<input type="checkbox" name="choices" value="Horror" onclick="checkIt(1);"
>Horror</span>
<span onclick="checkIt(2);">
<input type="checkbox" name="choices" value="Action" onclick="checkIt(2);"
>Action</span>
</form>
|