3

I am having an issue with JQuery attribute starts with selectors [name^="value"]. below is what i am trying to do

var parentContainer = $('#myparent');
$.each(parentContainer.find('*[name^="a[2].b[0].c"]'), function(){
 alert('Hi');               
});

Though the parentContainer have the elements with name starts with a[2].b[0].c still not able to alert 'Hi'.

But when i try to do it as mentioned below it works

var parentContainer = $('#myparent');
$.each(parentContainer.find('*[name^="a[2].b"]'), function(){
 alert('Hi');               
});

need ur help. Thanks in advance

Manish
  • 31
  • 2
  • 3
    Seems to work for me: http://jsfiddle.net/wWYfy/ – kei Jun 14 '11 at 16:03
  • 3
    The `*` in your selectors is superfluous. – BoltClock Jun 14 '11 at 16:06
  • @kei try putting 'a[3].b[2].c[0].d.e' as name attribute value. I have tried the same jsfiddle.net/wWYfy. Didn't worked for me. – Manish Jun 14 '11 at 19:00
  • @Manish Of course it won't work. That doesn't match `'*[name^="a[2].b[0].c"]'` It would, however, match `[name^="a[3].b[2].c"]` – kei Jun 14 '11 at 19:06
  • @kei i am trying to find out all the input elements which has name attribute starts with a[3].b[2].c in an html node say form. '*' ll help me to go through each child node in the form and [name^="a[2].b[0].c"] ll filter those elems. – Manish Jun 14 '11 at 19:23
  • @kei don't mean the index i am using in expression 'a[2].b[0].c' those are just for example. – Manish Jun 14 '11 at 19:24

1 Answers1

6

Have a look at the responses to this question.

The following quote could show the cause of your problem:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Square brackets are not valid characters for name (or id) attribute values, and while it will often still work, you may get unexpected results in some browsers.

This fiddle works fine for me in Firefox (only tried version 4), Safari 4 and 5, Chrome 12, IE8 and IE9 but fails (undefined is alerted) in IE6 and IE7.

Community
  • 1
  • 1
James Allardice
  • 156,021
  • 21
  • 318
  • 304
  • But if i have to map the html input element to an array in my form or i have a complex form with nth level of hierarchy like MyForm contains an array of FormA which containes an array of FormB which contains an array of FormC which contains a FormD which has a String property e eg.'a[3].b[2].c[0].d.e', What should i do in that case if the square brackets are not valid. – Manish Jun 14 '11 at 19:11
  • 1
    I'm afraid I don't quite follow you. Are you asking for a new naming system? I would suggest using something like `a3-b2-c0-d-e` if you really can't just use a descriptive name. – James Allardice Jun 14 '11 at 19:16