Reputation: 875
I have 4 radio input.
And I have assigned them hotkeys. (Hotkeys are 1,2,3 and 4)
Here is my html code:
<label>
<input type="radio" value="2" id="1" name="1">[c2]
</label>
<label>
<input type="radio" value="4" id="2" name="1">[c4]
</label>
<label>
<input type="radio" value="1" id="3" name="1">[c1]
</label>
<label>
<input type="radio" value="3" id="4" name="1">[c3]
</label>
and javascript code:
$(document).keypress(function(e) {
if(e.charCode == 49) {
console.log("1");
$('input:radio[id=1]').attr('checked',true);
}
if(e.charCode == 50) {
console.log("2");
$('input:radio[id=2]').attr('checked',true);
}
if(e.charCode == 51) {
console.log("3");
$('input:radio[id=3]').attr('checked',true);
}
if(e.charCode == 52) {
console.log("4");
$('input:radio[id=4]').attr('checked',true);
}
});
You can also see, I put console.log
events to script just to observe.
The strange thing for me, I can select redio buttons by their hotkeys only once per radio button.
*
If I press 1, it chooses the correct checkbox and gives me the correct console log.
Then I press 2, and works the same.
But then if I press 1 again, it gives me the console log but hotkey doesn't work.
Here is jsfiddle: https://jsfiddle.net/f07evno0/
How can I make hotkeys work more than once in one session?
Upvotes: 1
Views: 76
Reputation: 1864
You may have to use
$("input:radio[id=2]").prop("checked", true)
$(document).keypress(function (e) {
if (e.charCode == 49) {
console.log("1");
$('input:radio[id=1]').prop('checked', true);
}
if (e.charCode == 50) {
console.log("2");
$('input:radio[id=2]').prop('checked', true);
}
if (e.charCode == 51) {
console.log("3");
$('input:radio[id=3]').prop('checked', true);
}
if (e.charCode == 52) {
console.log("4");
$('input:radio[id=4]').prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>
<input type="radio" value="2" id="1" name="1">[c2]
</label>
<label>
<input type="radio" value="4" id="2" name="1">[c4]
</label>
<label>
<input type="radio" value="1" id="3" name="1">[c1]
</label>
<label>
<input type="radio" value="3" id="4" name="1">[c3]
</label>
Try it on https://jsfiddle.net/f07evno0/1/
Upvotes: 4
Reputation: 782
I dont find out the reason,but this code worked:
$(document).keypress(function(e) {
if(e.charCode == 49) {
console.log("1");
//$('input:radio[id=1]').attr('checked',true);
$('input:radio[id=1]')[0].checked= "checked"
}
if(e.charCode == 50) {
console.log("2");
//$('input:radio[id=2]').attr('checked',true);
$('input:radio[id=2]')[0].checked= "checked"
}
if(e.charCode == 51) {
console.log("3");
//$('input:radio[id=3]').attr('checked',true);
$('input:radio[id=3]')[0].checked= "checked"
}
if(e.charCode == 52) {
console.log("4");
//$('input:radio[id=4]').attr('checked',true);
$('input:radio[id=4]')[0].checked= "checked"
}
});
Upvotes: 1