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
  • 75,157
  • 39
  • 215
  • 276
  • 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
  • 74,352
  • 26
  • 153
  • 180
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
  • 74,352
  • 26
  • 153
  • 180
Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
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
  • 24,096
  • 8
  • 59
  • 61