Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery script adding id and using it doesn't work

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

like image 881
lost.design Avatar asked Dec 16 '15 15:12

lost.design


2 Answers

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>
like image 162
BenG Avatar answered Sep 30 '22 19:09

BenG


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>
like image 28
yukuan Avatar answered Sep 30 '22 20:09

yukuan