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?

SBB
  • 8,560
  • 30
  • 108
  • 223
  • Current code should work. `val()` returns `undefined` is the element it is called on does not exist. – techfoobar Jan 31 '14 at 14:24
  • 1
    possible duplicate of [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – Ram Jan 31 '14 at 14:25
  • have you tried typeof account !== 'undefined'? – euther Jan 31 '14 at 14:26
  • What @techfoobar said, the posted code does not throw an error, and works just fine -> http://jsfiddle.net/D3LrF/ – adeneo Jan 31 '14 at 14:31

2 Answers2

3

Don't call val()

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

and chack length -

if(account.length){

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
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()
Jai
  • 74,255
  • 12
  • 74
  • 103
  • That would tell me that it found the element but then i need the value of it as well. – SBB Jan 31 '14 at 14:28