最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery .val() returns undefined - Stack Overflow

programmeradmin5浏览0评论

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 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>
Share Improve this question asked Jul 27, 2016 at 13:42 pythonicpythonic 21.6k47 gold badges141 silver badges231 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

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

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!

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

发布评论

评论列表(0)

  1. 暂无评论