user2332475
user2332475

Reputation: 43

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.

Upvotes: 1

Views: 378

Answers (3)

SLaks
SLaks

Reputation: 887807

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.

Upvotes: 1

Gaucho_9
Gaucho_9

Reputation: 265

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.

Upvotes: 0

rahul maindargi
rahul maindargi

Reputation: 5655

try this

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

Upvotes: 0

Related Questions