3

im trying to use the code below to select a form element (i retrieve the values to validate the text)

$('#box1 [name=item[]]').val();
$('#box2 [name=item[]]').val();

i'm trying to get the value of the following

<form..>
   <div id='box1'> <input type='text' name='item[]'/> </div>
   <div id='box1'> <input type='text' name='item[]'/> </div>
</form>

I need to use 'item[]' with the square brackets [ ] because php can retrieve this data as an array

$data = $_REQUEST['item'];

Would return an array containing all the data in 'item'

The problem is the $('#box [name=item[]]').val() doesn't work, how would I get it to work or would there be another way to do this?

Tarang
  • 74,439
  • 37
  • 212
  • 270
  • you can try to escape your selector with `\` - see this thread: http://stackoverflow.com/questions/739695/jquery-selector-value-escaping for more info – JMax Oct 12 '11 at 08:41

3 Answers3

2

You need to escape the [ and ] in the jQuery selector, as they have a special meaning (attribute selectors):

$('#box1 [name="item\\[\\]"]').val();
$('#box2 [name="item\\[\\]"]').val();

jQuery documentation states:

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \.

Matt
  • 72,564
  • 26
  • 147
  • 178
1

if you could give the inputs a classname like "input_item" and than

$("input.input_item").each(function() {

    // do something with $(this).val()
});
Matt
  • 72,564
  • 26
  • 147
  • 178
Manuel van Rijn
  • 9,957
  • 1
  • 26
  • 50
0

Try -

$('#box1 input[name="item[]"]').val()

I've just added double quotes around the 'name' value and added the 'input' selector to the selector value.

Demo - http://jsfiddle.net/ipr101/JbW5m/

ipr101
  • 23,772
  • 7
  • 57
  • 61