Home > Mobile >  Jquery selectors with index in Ids
Jquery selectors with index in Ids

Time:05-30

working on a product detail page. i have itemname, itemdescription and itemprice input fields in a single item div. user can add mutiple item divs dynamically having multiple item input fields. I have placed the Ids of input fields as Itemname[0], itemdesc[0], itemprice[0] in a single item div. and obviously in next divs, it will be Itemname[1], itemdesc[1], itemprice[1] and so on. Problem is that i am not able to fetch the values of these input fields by providing their indexes for example: $('#itemname[0]').val(); gives me undefined. How can i achieve this? Thanks so much in advance

#Minimal Reproducible Example:#

<div id="itemset1">
        <input type="text" id="itemname[0]" value="Inventory item1">
        <input type="text" id="itemdesc[0]" value="Inventory item1 desc">
</div>
<div id="itemset2">
        <input type="text" id="itemname[1]" value="Inventory item2">
        <input type="text" id="itemdesc[1]" value="Inventory item2 desc">
</div>

How to fetch value of itemname[1] or itemname[0]? console.log($('#itemname[0]').val()); says undefined

CodePudding user response:

its a possible duplicate of https://stackoverflow.com/a/7396380/2242611 it can be achieved by providing id property in jquery selector syntax $('[id="itemname[0]"]').val()

CodePudding user response:

"The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined."

So with .val() you can only get and return values to input,select and textarea elements.

If you want to fill a div element with the values of an Array use text() instead.

Docs:
https://api.jquery.com/val/
https://api.jquery.com/text/

  • Related