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?
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[]"]');