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.
    – techfoobar
    Commented Jan 31, 2014 at 14:24
  • 1
    possible duplicate of Is there an "exists" function for jQuery?
    – Ram
    Commented Jan 31, 2014 at 14:25
  • have you tried typeof account !== 'undefined'?
    – euther
    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
    – adeneo
    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){

3
  • I need the value of that element though.
    – SBB
    Commented Jan 31, 2014 at 14:26
  • @SBB Sure... you can call val() if that exist, right ? Commented Jan 31, 2014 at 14:27
  • seems like more code than needed but i guess if thats the only way
    – SBB
    Commented Jan 31, 2014 at 14:28
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
  • That would tell me that it found the element but then i need the value of it as well.
    – SBB
    Commented Jan 31, 2014 at 14:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.