简体   繁体   中英

JS: “TypeError: 'undefined' is not an object”

var name = $("input[#name]").value;
var email = $("input[#email]").value;
var msg = $("input[#msg]").value;

var nameLength = name.length;
var emailLength = email.length;
var msgLength = msg.length;

As you can see, all I'm trying to do is to get the length of the value of the #email field. It works for both of the other fields, but not the email field. It give "TypeError: 'undefined' is not an object".

Any reason why?

I've tried in both Safari and Google Chrome, both gives the same error.

The HTML:

<div class="form-group">
  <label class="col-md-4 control-label" for="email">Email</label>  
  <div class="col-md-5">
    <input id="email" name="email" type="text" placeholder="Enter your email address
    here" class="form-control input-md" required="">
  </div>
</div>

You are trying to use a DOM property on a jQuery object. If you have a jQuery object, then you must either use the jQuery method .val() , not the DOM property .value or you have to reach into the jQuery object to get the DOM object which you can then use DOM properties on.

I'd suggest you change it to use the jQuery method for getting the value:

var name = $("input[#name]").val();
var email = $("input[#email]").val();
var msg = $("input[#msg]").val();

Or, for illustrative purposes, this would also work (get the DOM object out of the jQuery object and use .value ):

var name = $("input[#name]")[0].value;
var email = $("input[#email]")[0].value;
var msg = $("input[#msg]")[0].value;

Based on the HTML you've added to your question, you need to fix your selectors too. To target an id="xxx" , you just use $("#xxx") . No other part of the selector is required because ids must be unique in the entire document. So, if all your HTML works like the email part you've shown in your question, then you can use this:

var name = $("#name").val();
var email = $("#email").val();
var msg = $("#msg").val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM