how to extract data from a javascript attribute

0

I'm having a problem when taking the data from a data-id with javascript data, what I want to try if I have several buttons to say that each button has a different value until then it's fine but when calling each button with different values calls me first.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-id="sa!" onclick="funcionData()"> click1 </button>
<button type="button" id="button1" data-id="sasasa!" onclick="funcionData()"> click2 </button>
<script type="text/javascript">
function funcionData(){
alert($("#button1").data("id"));
}
</script>
</body>
</html>

I give you the example of something I want to do if you see button one as the data-id="sa!" attribute. and the button 2 with click2 with the data-id = sasasa "but at the moment of calling it, only the first and not the second return to me

    
asked by Matias 23.07.2018 в 19:06
source

2 answers

1

Concepts error, the ID is a unique identifier, if you are going to have different elements you should use classes.

You could pass the element where the event is done, by this in the html

function funcionData(el){
  alert($(el).data('id'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-id="sa!" onclick="funcionData(this)"> click1 </button>
<button type="button" id="button2" data-id="sasasa!" onclick="funcionData(this)"> click2 </button>

The way I would recommend would be to create a class and assign a listener for this class botones for the example, this will refer to the element where the event occurs, click for this case.

$(document).on('click','.botones',function(){
   alert($(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button"  class="botones" data-id="sa!" > click1 </button>
    <button type="button"  class="botones"  data-id="sasasa!" > click2 </button>
    
answered by 23.07.2018 / 19:11
source
0

First of all you should not have two elements with identical ids. The id must be unique throughout the sun. Second, you must pass the object to the function to be able to recognize which button was the one that was pressed. The correct way would be like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-id="sa!" onclick="funcionData(this)"> click1 </button>
<button type="button" id="button2" data-id="sasasa!" onclick="funcionData(this)"> click2 </button>
<script type="text/javascript">
function funcionData(boton){
alert($(boton).data("id"));
}
</script>
</body>
</html>
    
answered by 23.07.2018 в 19:09