1

I'm trying to get an array of elements with javascript or jQuery when the elements I want are a set with the same name prepared for being an array once I submit the form.

Much more understandable with the code:

<form>
    <!-- ... -->
    <input name='ciudades[]' id="cb_0" type='checkbox' style="display: none" checked="checked" value="ALICANTE_AER">ALICANTE_AER</input>
    <input name='ciudades[]' id="cb_1" type='checkbox' style="display: none" checked="checked" value="MALAGA_AER">MALAGA_AER</input>
    <input name='ciudades[]' id="cb_2" type='checkbox' style="display: none" checked="checked" value="MALLORCA_AER">MALLORCA_AER</input>
    <input name='ciudades[]' id="cb_3" type='checkbox' style="display: none" checked="checked" value="VALENCIA_AER">VALENCIA_AER</input>
    <!-- ... -->
</form>

I've tried to get an array with all the elements named 'ciudades[]' with these two ways unsuccesfully:

var cb_ciudades = document.getElementsByTagName('ciudades[]');

and

var cb_ciudades = document.getElementsByTagName('ciudades');

but I'm ending with an empty array in both cases. How could it be done?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
javier_domenech
  • 5,995
  • 6
  • 37
  • 59

3 Answers3

2

getElementsByTagName works by tag name, e.g. input or div or span, not the name attribute.

If you want to get those elements by their name, you can use querySelectorAll:

var list = document.querySelectorAll('input[name="ciudades[]"]');

querySelectorAll is supported by all modern browsers, and also IE8.

Or as you've tagged your question jquery:

var $list = $('input[name="ciudades[]"]');
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You need to get the elements by attribute as ciudades[] is value of name attribute. however you have used get by tag name method. You can get them using jquery:

$('[name="ciudades[]"]')

If you want the solution in javascript then refer https://stackoverflow.com/a/15342661/1719752

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

javascipt

var inputs = document.getElementsByTagName('input');
var myElements = [];
for(var i =0; i < inputs.length; i++){
    if(inputs[i].getAttribute('name') == 'ciudades[]'){
        myElements.push(inputs[i]);
    }
}

jQuery

$('[name="ciudades[]"]')
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53