I have a few checkboxes that I need to be selected with the enter key instead of the space bar when it has focus. I have the code below that works for one check box, but I need multiple checkboxes. I know the id tag needs to be unique, but I'm not sure how to do it.
$(document).ready(function () {
$('#mycheckbox').on('keypress', function (event) {
if (event.which === 13) {
this.checked = !this.checked;
}
});
});
<input type="checkbox" name="Colors" value="Bike" id="mycheckbox">My text<br>
I'm trying to get this to work on all the checkboxes not just the one with the mycheckbox id.
Here's my full code so far:
`
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-
latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input:checkbox').on('keypress', function (event) {
if (event.which === 13) {
$(this).prop('checked', !$(this).prop('checked'));
}
});
});
</script>
</head>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></
script>
<textarea class="textfield" id="form1" name="form1">My text
here</textarea>
<div class="taglist">
<label><input type="checkbox" value="Value 1">Value 1</label>
<label><input type="checkbox" value="Value 2">Value 2</label>
<label><input type="checkbox" value="Value 3">Value 3</label>
<label><input type="checkbox" value="Value 4">Value 4</label>
<label><input type="checkbox" value="Value 5">Value 5</label>
</div>
<script type="text/javascript">
function updateTextArea() {
var allVals = $('#form1').data('initialVal'),
lineCount = 1;
$('.taglist :checked').each(function(i) {
allVals+= (i != 0 || allVals.length > 0 ? "\r\n" : "") + $(this).val
();
lineCount++;
});
$('#form1').val(allVals).attr('rows', lineCount);
}
$(function() {
$('.taglist input').click(updateTextArea);
$('#form1').data('initialVal', $('#form1').val());
updateTextArea();
});
</script>
</body>
</html>
`
Sounds like you are trying to get this to work on all checkboxes? In that case use $( ":checkbox" ) instead of $('#mycheckbox')
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