Count and define number of inputs with specific ID prefix

tony :

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)?

Mamun :

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"/>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7112&siteId=1