问题
I'm the beginner of JS. I try to get input from the HTML form. And print words out from function. I have read JS in W3. However, it keeps going wrong. Could somebody give me a hand.
HTML - about the form
<form method="get">
<h2>Please leave your contact information for us</h2>
<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" name="firstName" placeholder="Your First Name"><br>
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" name="LastName" placeholder="Your last Name"><br>
<label for="email">E-mail:</label>
<input type="e-mail" id="email" name="eMail"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="passWord"><br>
<label for="suGession">sub gesstion:</label><br>
<textarea name="suggestion" id="suGession" cols="30" rows="10"></textarea>
<br>
<br>
<p>What do you usually cook?</p>
<input type="text">
<button type="submit" onclick="welcome()">Give Us Help</button>
</form>
My JS code
var first = document.getElementById("FirstName");
var last = document.getElementById("LastName");
function welcome(){
var welcomeF = "Welcome" + first +" "+ last;
return welcomeF;
}
console.log(welcome());
回答1:
Use first.value to get the value of the element & use onSubmit attribute in instead of using onclick.
Have a look at this code, I did some changes in your code.
Javacript :
function welcome(){
var first = document.getElementById("FirstName").value;
var last = document.getElementById("LastName").value;
var welcomeF = "Welcome " + first +" "+ last;
console.log(welcomeF);
window.alert(welcomeF);
return false; //To prevent it from going into next page.
}
Html :
<form onSubmit = "return welcome();">
<h2>Please leave your contact information for us</h2>
<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" name="firstName" placeholder="Your First Name"><br>
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" name="LastName" placeholder="Your last Name"><br>
<label for="email">E-mail:</label>
<input type="e-mail" id="email" name="eMail"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="passWord"><br>
<label for="suGession">sub gesstion:</label><br>
<textarea name="suggestion" id="suGession" cols="30" rows="10"></textarea><br><br>
<p>What do you usually cook?</p>
<input type="text">
<button type="submit" >Give Us Help</button>
回答2:
You need to change:
var welcomeF = "Welcome" + first +" "+ last;
to:
var welcomeF = "Welcome" + first.value +" "+ last.value;
first and last are just references to the dom nodes, not the value in them
来源:https://stackoverflow.com/questions/31195709/js-input-user-name-and-print-it-out