Newbie- I want to do 2 things with these checkboxes:
Below is sample code. I am using the checkboxes as a group.
Does any one have any suggestions?
<!doctype html>
<head>
<title>test Radio buttons checkbox</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input:checkbox[name=Colors]').keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
Checkbox_to_RadioButton(this);
alert("Enter key was pressed");
}
event.stopPropagation();
});
$('input:checkbox[name=Colors]').click(function(){
Checkbox_to_RadioButton(this);
});
});
function Checkbox_to_RadioButton(box){
$('input:checkbox[name=' + box.name + ']').each(function(){
if (this != box)
$(this).attr('checked', false);
});
}
</script>
</head>
<body>
<h1>test Radio buttons checkbox</h1>
<form name="form1">
<input type="text" id="dname" name="dname"><br>
<input type="checkbox" id="Colors" name="Colors" value="Red" />Red<br />
<input type="checkbox" id="Colors" name="Colors" value="Blue" />Blue<br />
<input type="checkbox" id="Colors" name="Colors" value="Green" />Green<br />
<input type="checkbox" id="Colors" name="Colors" value="Yellow" />Yellow<br />
<br>
</form>
</body>
</html>
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
Since a checkbox is an interactive control, it must be focusable and keyboard accessible. If the role is applied to a non-focusable element, use the tabindex attribute to change this. The expected keyboard shortcut for activating a checkbox is the Space key.
The checkbox button is similar to a checkbox in that it presents a user with a binary choice for an item. However, the only action a user can take is to add (or remove) an entity. When a user clicks the checkbox button, the entity is stored, similar to an 'add to cart' experience, until the user saves changes.
r3wt's approach works beautifully, but I noticed on my forms that pressing Enter
would also submit the form or otherwise do something else unwanted. Adding e.preventDefault();
prevents the default browser action when pressing enter on the checkbox.
$('input:checkbox').keypress(function(e){
e.preventDefault();
if((e.keyCode ? e.keyCode : e.which) == 13){
$(this).trigger('click');
}
});
I found the recommended solution to be too bloated. this works better
$('input:checkbox').keypress(function(e){
if((e.keyCode ? e.keyCode : e.which) == 13){
$(this).trigger('click');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With