
Let us assume, I have few DIV elements and each element has a unique id, prefixed with a number sequence. I want to get the number (only) from each element’s id, when clicked.
I am sharing two examples here.
Example 1
In the first example, I have two DIV elements, each with a unique ID suffixed with an integer value.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<p>Click the Elements below to get the number from its ID.</p>
<div id="div1">
Contents in DIV1
</div>
<div id="div2">
Contents in DIV2
</div>
<p id="result"></p>
</body>
<script>
$(document).ready(function () {
$('div').click(function () {
var i = $(this).attr('id').replace('div', '');
$('#result').text(i);
});
});
</script>
</html>In the above script, I am using "two" jQuery methods to extract the number from each element. The first method is .attr(), which takes a parameter as "id". The second method is .replace(), which takes "two" parameters,
* the string value we want to replace
* the value to replace.
The second parameter in the ".replace()" method is blank. So, it replaces the string value with nothing and returns the integer value.
Example 2
Here’s another example.
I have a table. Each row has a textbox, and two DIV elements. Each element has a unique id prefixed by a number. The first field (input box) will accept a number as "Quantity". The second is a DIV element, which has a predefined value as "Price". Once I enter value in the "Quantity" field, the script will calculate Quantity and Price and show the total in the last DIV element of the row.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<p>Enter a number in the first (Quantity) field.
It will calculate the Quantity, multiplied by the Price and show the total amount.</p>
<div>
<div><input placeholder="Qty." id="qty1" /></div>
x <div id="price1">2000</div>
= <div id="total1"></div><br />
<div><input placeholder="Qty." id="qty2" /></div>
x <div id="price2">1600</div>
= <div id="total2"></div><br />
<div><input placeholder="Qty." id="qty3" /></div>
x <div id="price3">2100</div>
= <div id="total3"></div>
</div>
</body>
<script>
$(document).ready(function () {
$('input').keyup(function () {
var i = $(this).attr('id').replace(/qty/, '');
if ($(this).val() != "") {
var p = $('#price' + i).text();
$('#total' + i).text($(this).val() * parseInt(p));
}
});
});
</script>
</html>