1

I have a block of code that looks like this:

//Account Number account = $(msg).find('[name=account_number]').val(); if(account){ $('#progressUpdates').append('<span class="glyphicon glyphicon-ok"></span>&nbsp;&nbsp;Found Account Number<br />'); }else{ $( '#progressUpdates').append('<span class="glyphicon glyphicon-remove"></span>&nbsp;&nbsp;Account Number not found<br />'); } 

The problem is, if the element that is being assigned to account doesn't exist, it throws an error. I tried doing :

if(account.length){} 

But the issue isn't with the if statement, its assigning the variable. Is there a better solution to this?

4
  • Current code should work. val() returns undefined is the element it is called on does not exist. Commented Jan 31, 2014 at 14:24
  • 1
    possible duplicate of Is there an "exists" function for jQuery? Commented Jan 31, 2014 at 14:25
  • have you tried typeof account !== 'undefined'? Commented Jan 31, 2014 at 14:26
  • What @techfoobar said, the posted code does not throw an error, and works just fine -> jsfiddle.net/D3LrF Commented Jan 31, 2014 at 14:31

2 Answers 2

3

Don't call val()

account = $(msg).find('[name=account_number]');

and chack length -

if(account.length){

Sign up to request clarification or add additional context in comments.

3 Comments

I need the value of that element though.
@SBB Sure... you can call val() if that exist, right ?
seems like more code than needed but i guess if thats the only way
1

instead of this:

account = $(msg).find('[name=account_number]'); 

try with removing .val():

account = $(msg).find('[name=account_number]'); 

okay then you have to check for length in your if:

if(account.length){ 

or if you want the value out of it as suggested by Anton:

account.val() 

1 Comment

That would tell me that it found the element but then i need the value of it as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.