Close

How to find list of input fields values with similar ID in Javascript

Sometimes we may need to find the values of different IDs of same type of elements, like input fields for any web page who have similar patterns in their IDs. Look at the below scenario

<input name="order_inv_id_<?php echo $count; ?>" id="order_inv_id_<?php echo $count; ?>" type="hidden" value="" />

The above line will create ids like “order_inv_id_1”, “order_inv_id_2”, “order_inv_id_3” and so on. So, how to get values from this ids? Use the simple code in JavaScript to find out.

<script>
var ordered_inventory_id = document.querySelectorAll('[id^="order_inv_id_"]');  
	//console.log('id = '+ordered_inventory_id);
	var selected_ids=[];

	for (let inv_id of ordered_inventory_id) 
	{
		if(inv_id.value!="")
		{
			//console.log("value = "+inv_id.value);
			selected_ids.push(inv_id.value);
		}
	}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *