简体   繁体   中英

How to access indexed id in javascript

I am having trouble in accessing an element to validate it.

For example, if I am generating a dynamic table from a database and I have a code that looks something like this:

i=0;

while($row as values){

    <input type='text' id='quantity[$i]' name='quantity[$i]' value=''>
    <input type='text' id='quantity_req[$i]' name='quantity_req[$i]' value=''>

    $i++;
}
<input type='hidden' id='i' name='i' value='$i'>

I can use $('#i').val() to get the value of i, but how can I get the values of the text fields?

$('#quantity[i]').val(); and $('#quantity[i]').val(); doesn't work, javascript seem to think of "#quantity[i]" as a string, even though I have given 'i' a value through a for loop.

I also tried $('#quantity' +i).val() but it's not working too.

javascript seem to think of "#quantity[i]" as a string

That's right. "#quantity[i]" is a string; Javascript doesn't look at parts of a string that happen to name variables.

You need to concatenate the value into your string, as you tries at the end.
However, you also need to concatenate in the brackets; you concatenated #quantity1 , which isn't the string you're looking for.

You also need to escape the brackets, or jQuery will parse them as an attribute selector.

try this

var ival=$('#i').val();
$('#quantity\\[' +ival+'\\]').val()

I think you are mixing javascript variables and PHP variables.

PHP variables are with the '$' before the name of the variable.

If you want to get the value of the inputs you have to use the PHP variable, no te letter 'i' like you are using.

You have to do like answer from rahul maindargi and it should works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM