Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .val() returns undefined

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>
like image 316
pythonic Avatar asked Jul 27 '16 13:07

pythonic


People also ask

What does VAL () return in jQuery?

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.

What does val() do?

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.

How can we use jQuery to Get the value of an input element with id name?

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.


1 Answers

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;"> 
like image 195
eisbehr Avatar answered Sep 25 '22 09:09

eisbehr