Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - if href attr == ""

I am trying to find out if a href attr is empty do something, my code is as follows...

jQuery('#sidebar a').click(function() {

     var bob = jQuery(this).attr("href");

     if(jQuery(bob).attr() == "") {
            alert('I am empty href value');
        }

    });

I am not sure where I am going wrong? Any advice? Thanks!

like image 412
Phil Avatar asked Jul 01 '11 10:07

Phil


4 Answers

You're passing bob into jQuery as a selector. Just test it directly:

jQuery('#sidebar a').click(function() {

    var bob = jQuery(this).attr("href");

    if (bob == "") {
        alert('I am empty href value');
    }

});

Or better yet, just:

    if (!bob) {

Gratuitous live example

like image 99
T.J. Crowder Avatar answered Oct 12 '22 02:10

T.J. Crowder


You are setting a variable and then never checking it. Personally, I wouldn't even create a variable; Just do the check.

jQuery('#sidebar a').click(function() {
    if(jQuery(this).attr("href") == "") {
        alert('I am empty href value');
    }
});
like image 42
Michael Irigoyen Avatar answered Oct 12 '22 03:10

Michael Irigoyen


use this instead

jQuery('#sidebar a').click(function() {

 var bob = jQuery(this).attr("href");

 if(bob === "") {
        alert('I am empty href value');
    }

});
like image 34
bingjie2680 Avatar answered Oct 12 '22 01:10

bingjie2680


Answer is already given by great guys.

just check if(bob=="")

I would add one more line. Just for safety you can trim bob using jQuery.

bob = jQuery.trim(bob);

This will make the validity a bit stronger.

like image 32
MAK Ripon Avatar answered Oct 12 '22 01:10

MAK Ripon