In jQuery, when we want to get the integer part of an “id” on click of a button element , we generally do it by using the substring() method, by taking the initial point from where the integer may start.
But we can also do this using a different approach
In this example we have multiple images (3) with different ids which are strings suffixed with incrementing integers, though the data type of the entire id remains string.
<input type="image" id="imgAdd1" ....../> <input type="image" id="imgAdd2" ....../> <input type="image" id="imgAdd3" ....../>
Now we can know which image button has been clicked by the following method –
$( ".btnAdd").click(function () { var index = parseInt($(this).attr("id").match(/imgAdd(\d+)/)[1], 10);. . });
What the above code does is-
1.It first fetches the attribute ID of the clicked image,
2.then matches the pattern ” imgAdd (\d+) ” which means “imgAdd” suffixed by one or more integers.
3.Then it takes the first substring ( which is the integer part),
4.and converts it an integer of base 10.
Now you can get your integer part.