The relevant part of the code is shown below. When I click the Submit button, on the alert box, I get undefined, rather than the typed email. What mistake am I doing here?
<form action="page2.php" method="post" onsubmit="myFunction()" id="form1">
......
<input type="text" name="YourEMail" style="width: 250px;">
<input type="submit" name="submit" value="Submit"> <br>
......
</form>
<script>
$('#form1').submit(function() {
//your validation rules here
var email = $('#YourEMail').val()
alert(email)
//if(email.length == 0)
return false;
//else
// return true;
});
</script>
The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
The val() method is an inbuilt method in jQuery which is used to returns or set the value of attribute for the selected elements. This method apply on the HTML form elements.
Answer: Use the jQuery val() Method You can simply use the jQuery val() method to get the value in an input text box. Try out the following example by entering something in the text input box and then click the "Show Value" button, it will display the result in an alert dialog box.
YourEMail
is the name
, not the id
:
var email = $('input[name=YourEMail]').val();
Or change the input
to have the id
:
<input type="text" id="YourEMail" name="YourEMail" style="width: 250px;">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With