1

I have some input fields in the following format:

<input name='date_of_birth[month]' type='text' />
<input name='date_of_birth[day]' type='text' />
<input name='date_of_birth[year]' type='text' />

Is there a way to select all the values of these fields in jQuery?

GSto
  • 41,512
  • 37
  • 133
  • 184

2 Answers2

5

The $.map method may be better in this case:

var dobArray = $.map($('input[type=text][name^=date_of_birth]'),function(){
  return this.value;
});

and to make it a date string,

var dobString = dobArray.join("/");
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • 1
    Keep in mind that the order of the array will be based on the DOM order of the input elements. – Kevin B May 10 '12 at 20:22
2
$(":text[name^='date_of_birth']").each(function (){alert(this.value)});

http://jsbin.com/emumef/edit#javascript,html

according to @gordon about speed - this will be faster: ( reduce extension overhead)

 $("input[type='text'][name^='date_of_birth']")
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • +1, note that `:text` isn't efficient selector. you should replace it with `input[type='text']` – gdoron May 10 '12 at 20:12
  • @gdoron input type text is better ? – Royi Namir May 10 '12 at 20:12
  • _"Because `:text` is a jQuery extension and not part of the CSS specification, queries using :text cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use `[type="text"]` instead."_ – gdoron May 10 '12 at 20:13
  • One more thing if I may, [Though `$()` with DOM element isn't expensive](http://stackoverflow.com/q/10433014/601179), you should use `this.value` instead of `$(this).val()`. – gdoron May 10 '12 at 20:16
  • @gordon, yeah i know . its an instinct ...:) – Royi Namir May 10 '12 at 20:17