eclipseIzHere eclipseIzHere - 3 months ago 8
Javascript Question

Form element not sending its values

So I have a form:

<form name="htmlform" method="post" action="test.html">
<input type="text" id="first" placeholder="First Name" required>
<input type="text" id="last" placeholder="Last Name" required>
<input type="email" id="email" placeholder="Email" required>
<textarea id="comments" name="comments" placeholder="Message" required></textarea>
<button name="send" type="submit" class="submit">SEND</button>
</form>


and after the user submits the form, it is sent to test.html through POST method. And this is the code on test.html.

<div id="targetDiv"></div>

</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var first=$("#first").val();
var last=$("#last").val();
var email=$("#email").val();
var comments=$("#comments").val();
var txt1="Welcome " +first+" "+last;
var txt2="Your Email is " +email;
var txt3="Your Message is "+ comments;
$("#targetDiv").append(txt1+"<br>"+txt2+"<br>"+txt3);
</script>


but when the user submits, #targetDiv always prints out:

Welcome undefined undefined
Your Email is undefined
Your Message is undefined

Answer

Your form and the div you are trying to append values to need to be in the same html file unless you are working with a server. Also give your submit an event listener to call all the code you already have. Like this:

$(".submit").on("click", function(e) {
  e.preventDefault();
  var first=$("#first").val();
  var last=$("#last").val();
  var email=$("#email").val();
  var comments=$("#comments").val();
  var txt1="Welcome " +first+" "+last;
  var txt2="Your Email is " +email;
  var txt3="Your Message is "+ comments;
  $("#targetDiv").append(txt1+"<br>"+txt2+"<br>"+txt3);
});