5120bee 5120bee - 3 months ago 9
Javascript Question

Javascript: How use a loop function to show all the user input in one single alert box?

I'm trying to write a function that will show an Alert Box for all the data entered by the user in the form. I must do it only in simple javascript (sorry no jQuery). My HTML is as follows:

<form method="POST">
<label class="form">Name: </label><input type="text" name="name" id="name"><br>
<label class="form">Address: </label><input type="text" name="address" id="address"><br>
<label class="form">Email: </label><input type="text" name="email" id="email"><br>

<button id="submit" type="submit" value="submit" onclick="showAlert()">
Submit
</button>
</form>


My javascript:

function showAlert() {
var userInputs = document.getElementsByTagName("input");

for (var i=0; i < userInputs.length; i++) {
alert(userInputs.value + " ");
//Basically my idea would be to implement a loop for as many input fields,
//run through all of them, then display ONE SINGLE alert box containing all the
//data entered by the user. But I'm having trouble with how to implement the loop.
}
}


How do I implement the loop?

I have written another function that achieves the same effect but it involved writing a long, tedious list of variables for each input field and I don't want to do that since it's messy:

function alternateShowAlert() {
var name = document.getElementById('name').value;
var address = document.getElementById('address').value;
var email = document.getElementById('email'.value;

alert(name + " " + address + " " + email)

//This function, although it works fine, will be too long and tedious if I have
//more input fields such as age, city, state, country, gender, etc. I want to put
//it in a loop format but how do I do this?
}

Answer
function showAlert() {
  var userInputs = document.getElementsByTagName("input");
  var alertBody = "";
  for (var i=0; i < userInputs.length; i++) {
    alertBody += userInputs[i].value + " ";
  }
  alert(alertBody);                                                                                                                                            
}

document.getElementsByTagName() returns an array, so you need to access the elements of the array using their index: userInputs[i].

Or you can use Array.prototype.forEach. See the example below.

function showAlert() {
  var userInputs = document.getElementsByTagName("input");
  var alertBody = "";
    Array.prototype.forEach.call(userInputs, function(element) {
      alertBody += element.value + " ";
    });
  alert(alertBody);                                                                                                                                            
}
Comments