I have a table with 33 inputs with ID's ranging from 1 - 33. So for example they range from "price-1" all the way to "price-33"
Instead of individually define these elements one by one like this:
var p1 = document.getElementById("price-1");
var p2 = document.getElementById("price-2");
How can I automatically count (perhaps count by the price-
prefix?) and define each of these elements using JavaScript (or jQuery if it's easier)?
You can try using Attribute selectors ( starts with:- [attr^=value]
):
Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.
Demo: Using vanilla JS:
var elList = document.querySelectorAll('[id^=price-]');
console.log(elList.length); //5
//loop throgh all the elements whose id starts with price-
var data = {};
elList.forEach(function(el){
data[el.id] = el.value;
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="price-1" value="100"/>
<input id="price-2" value="200"/>
<input id="price-3" value="300"/>
<input id="price-4" value="400"/>
<input id="price-5" value="500"/>
OR: Using jQuery
var count = $('[id^=price-]').length;
console.log(count); //5
//loop throgh all the elements whose id starts with price-
var data = {};
$('[id^=price-]').each(function(){
data[this.id] = this.value;
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="price-1" value="100"/>
<input id="price-2" value="200"/>
<input id="price-3" value="300"/>
<input id="price-4" value="400"/>
<input id="price-5" value="500"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With