Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count and define number of inputs with specific ID prefix

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

like image 578
tony Avatar asked Dec 14 '22 09:12

tony


1 Answers

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"/>
like image 79
Mamun Avatar answered Dec 17 '22 22:12

Mamun