I have 3 buttons with same ID. I need to get each button’s value when it’s being clicked.
<button id="xyz" type="button" class="btn btn-primary" value="1">XYZ1</button>
<button id="xyz" type="button" class="btn btn-primary" value="2">XYZ2</button>
<button id="xyz" type="button" class="btn btn-primary" value="3">XYZ3</button>
Here is my current jQuery script:
$("#xyz").click(function(){
var xyz = $(this).val();
alert(xyz);
});
But it works only for the first button, clicking on the other buttons are being ignored.
You have invalid HTML. You can’t have more than one element in a page with the same
idattribute value.Quoting the spec:
Solution: change from
idtoclass:And the jQuery code:
jQuery
#idselector docs:If you look at the jQuery source you can see when you call
$with an id selecor-($("#id")), jQuery calls the native javascriptdocument.getElementByIdfunction:Though, in the spec of
document.getElementByIdthey didn’t mention it must return the first value, this is how most of (maybe all?) the browsers implemented it.DEMO