SBB
SBB

Reputation: 8970

Checking if element exists with jQuery

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?

Upvotes: 1

Views: 79

Answers (2)

Jai
Jai

Reputation: 74738

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

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Don't call val()

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

and chack length -

if(account.length){

Upvotes: 3

Related Questions