LetsSeo LetsSeo - 3 months ago 15
Javascript Question

jQuery hotkeys works only once

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?

Answer

You may have to use $("input:radio[id=2]").prop("checked", true)

Try it on https://jsfiddle.net/f07evno0/1/