gsamaras gsamaras - 3 months ago 9
HTML Question

Getting two strings as input from user, not the button value

I have this code:

<!DOCTYPE html>
<html>
<body>

<form id="frm1" action="form_action.asp">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of each element in the form.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("frm1");
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
if(x.elements[i].value)
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>


Which will treat "Submit" string from the Submit button as an input string to. Obviously, assuming that the user won't input "Submit", I could hardcode-check if the value is "Submit" and skip it.

Isn't there any other way?

Answer

I could hardcode-check if the value is "Submit" and skip it.

Checking the value doesn't work because the user might actually type the word "Submit".

You can test the type of the elements:

if (x.elements[i].type === "text") { ... }

Or you can just select the text elements directly using the querySelectorAll() method:

function myFunction() {
    var x = document.querySelectorAll("#frm1 input[type='text']");
    var text = "";
    var i;
    for (i = 0; i < x.length ;i++) {
        text += x[i].value + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}
<form id="frm1" action="form_action.asp">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br><br>
  <input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of each element in the form.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

Comments