Hi I’m a bit new to jQuery. I’m trying to get the key value from a button id which is an array when clicked as shown below:
JavaScript
x
<button id="button[1]">Submit</button>
<button id="button[2]">Submit</button>
<button id="button[3]">Submit</button>
<button id="button[4]">Submit</button>
The expected result is when clicked is 1 or 2 or etc.
In PHP I would achieve this by getting the name which is an array also as shown below:
JavaScript
<html>
<button name="button[1]">Submit</button>
<button name="button[2]">Submit</button>
<button name="button[3]">Submit</button>
<button name="button[4]">Submit</button>
</html>
<?php
key($_POST['button']);
?>
How would I achieve this using jQuery?
Advertisement
Answer
The id
attribut is a unique label you give to an element, it is a string value and should be used only for selection. So firstly you can’t just cast a string button[1]
to an array, but this is a misuse of id
.
You should use the value
attribut to share this kind of information, like <button id="button1" value="1">text here</button>
and read it with $('#button1').value()