Reputation: 17
I'm trying to get an alert box to appear with a message contain both pre-defined text and user inputed text.
What I have so far are two input fields for first and last name and a submit button. It currently shows the alert popup with the pre-defined text but the user input just comes up as 'undefined'. Could you let me know where I might have gone wrong?
The code is as follows:
<form>
<p>First name: <input type="text" id="fname" name="firstname" value=""></p>
<p>Last name: <input type="text" id="lname" name="lastname" value=""></p>
<p><input type="button" value="Submit" id="namebutton" /></p>
<script>
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
document.getElementById("namebutton").addEventListener("click", function() {
alert('Hello ' + fname.value);
})
</script>
</form>
Upvotes: 1
Views: 2734
Reputation: 65806
Your fname
variable is already set up to store fname.value
. Then, in your alert
, you try to get the .value
of that, and there is no .value
property of the string returned by .value
(i.e. fname.value.value
).
In general, it's not a good idea to set a variable directly to some property of a DOM object, because if you decide later on in your code that you'd like to get the value of some other property, you have to re-scan the DOM for the same element you already scanned it for. Set your variables up to be references to the element, then get the various properties when you need them. This will not cause the document to be re-scanned to find the element.
<form>
<p>First name: <input type="text" id="fname" name ="firstname"></p>
<p>Last name: <input type="text" id="lname" name="lastname"></p>
<p><input type="button" value="Submit" id="namebutton"></p>
<script>
// Just get a reference to the element
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
document.getElementById("namebutton").addEventListener("click", function () {
// Then, use the properties of the (already gotten) elment as you need them:
alert('Hello ' + fname.value + " " + lname.value);
})
</script>
</form>
NOTES:
value
attribute is only necessary on a text field when you
want that text field to have a default value. If not, you can omit
the attribute.<tag />
) used by others. This is an old syntax that can cause
problems when not used properly and actually gains you nothing in
your code. That trailing slash is actually ignored by the browser.
Read this for what that syntax is and why you should not use it.Upvotes: 6