user3666951
user3666951

Reputation: 23

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>

Upvotes: 0

Views: 12673

Answers (1)

jfriend00
jfriend00

Reputation: 708026

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();

Upvotes: 4

Related Questions