i am trying to use my keyboard to click on a button using the id.
For some buttons i had to set the ID, which actually works. But as soon as i try to use the keyboard for the buttons where i set the id, it won't work.
I am not getting any errors and since adding the id to the element works, i am kinda confused why i cannot use the new set id later in the code.
//setting id for first button (works)
$( "a:contains('Im Verband freigeben')" ).attr('id', 'freigabe-verband');
//setting id for second button (works aswell)
$( "a:contains('Vorheriger Einsatz')" ).attr('id', 'vorheriger-einsatz');
$( document ).keydown(function(e) {
if (e.keyCode == 39) {
//works, id is available, not set by me
$("#alert_next").click();
} else if (e.keyCode == 38){
// doesn't work, but id is set
$("#freigabe-verband").click();
} else if (e.keyCode == 40){
// doesn't work, but id is set
$("#vorheriger-einsatz").click();
}
return e.returnValue;
});
Anyone know why? https://i.imgur.com/uy6oGFJ.png
To click a dom element, use:-
$('#freigabe-verband')[0].click();
or
$('#freigabe-verband').get(0).click();
Example
$("a").attr('id', 'test');
$(document).keydown(function(e) {
$('#test')[0].click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://stackoverflow.com">link</a>
It doesn't make sense. I copy your code and create a plunkr, it works well. http://plnkr.co/edit/Eb5QF6mB97Js41NFbr8J?p=preview
// Code goes here
$(function() {
//setting id for first button (works)
$( "a:contains('Im Verband freigeben')" ).attr('id', 'freigabe-verband');
//setting id for second button (works aswell)
$( "a:contains('Vorheriger Einsatz')" ).attr('id', 'vorheriger-einsatz');
$( document ).keydown(function(e) {
if (e.keyCode == 39) {
//works, id is available, not set by me
$("#alert_next").click();
} else if (e.keyCode == 38){
// arrow up
$("#freigabe-verband").click();
} else if (e.keyCode == 40){
// arrow down
$("#vorheriger-einsatz").click();
}
return e.returnValue;
});
}
);
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<a href="#" onclick="alert('a');">Im Verband freigeben</a><br>
<a href="#" onclick="alert('b');">Vorheriger Einsatz</a>
</body>
</html>
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