pythonic
pythonic

Reputation: 21625

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>

Upvotes: 6

Views: 25502

Answers (3)

Naser Nikzad
Naser Nikzad

Reputation: 941

in my case it was because different element types had same id.

Upvotes: 0

Hitesh Misro
Hitesh Misro

Reputation: 3461

Check this working fiddle https://jsfiddle.net/3h4n6qfe/1/

You are calling a id and jQuery returning it as null as there is no id for your input field

Modify from:

<input type="text" name="YourEMail" style="width: 250px;"> 

To:

<input type="text" name="YourEMail" id="YourEMail" value="My Email" style="width: 250px;">

and you're good to go!

Upvotes: 2

eisbehr
eisbehr

Reputation: 12452

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;"> 

Upvotes: 14

Related Questions