getElementsByTagName multiple tags

4.9k views Asked by At

I want get all my input and select elements off my page HTML. I've tried getElementsByTagName('input,select') but it does not work.

My code HTML and JavaScript:

function myFunction() {
var data =  [];
var data1 = [];
var data2 = [];
for (var i = 0; i < 10; ++i) {

  
var x = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("name"); 
var y = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("type");
var z = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("maxlength");
  data.push(x);
  data1.push(y);
  data2.push(z);
  location.href ="ttt.php?name=" + data + "&active=" + data1 + "&data2=" + data2
}  

}
<select name="CIV"><option selected="selected" value=""></option><option selected="selected" value="">Mr</option><option selected="selected" value="">Mme</option></select>
<input type="text" size="20" name="first_name" id="first_name" maxlength="50" class="cust_form" value="">
<input type="text" size="20" name="last_name" id="last_name" maxlength="50" class="cust_form" value="">
<input type="text" size="20" name="address3" id="address3" maxlength="50" class="cust_form" value="">

1

There are 1 answers

0
El'Magnifico On BEST ANSWER

You should access the elements separately; INPUT and SELECT. BTW, Select element doesn't have type and maxlength attributes.

function myFunction() {
  var nameData =  [];
  var typeData = [];
  var maxLengthData = [];
  var input = document.getElementsByTagName("INPUT")
  var select = document.getElementsByTagName("SELECT")

  // Targeting the first 9 of elements of input collections and select collections
  // Assuming you understand what you are doing here
  for (var i = 0; i < 10; ++i) {
    nameData.push( input[i].getAttribute( 'name' ) );
    nameData.push( select[i].getAttribute( 'name' ) );
    typeData.push( input[i].getAttribute( 'type' ) ); // Select element doesn't have type attribute
    maxLengthData.push( inputt[i].getAttribute( 'maxlength' ) ); // Select elemnt doesn't have maxlength attribute

    // Assuming you understand what you are doing to build your url here
    location.href ="ttt.php?name=" + nameData + "&active=" + typeData + "&data2=" + maxLengthData
  }  

}

Please, read more on HTML elements and their attributes. Also, read more on pure JavaScript.

Note: this has not been tested yet. Try it and let me know if it does what you you want it to do.