KBK
KBK

Reputation: 375

jquery on click get value undefined

<script>
$(document).on('click', '.nav-li', function () {
    //alert("Clicked");
    var url = $(this).attr("href");
    alert(url);
});
</script>

<section style="background-image: url('img/nav-x.png');background-repeat: repeat-x;">
    <div class="container">
        <div class="row">
            <div class="col-sm-10 col-sm-offset-1">
                <div class="row">
                    <ul class="col-sm-12 nav">
                        <li href "" style="text-align:center;" class="nav-li">HOME
                            <img src="img/home.png" style="position: absolute;z-index: 100;right: 12px;top: -7px;" class="hrv-img" />
                        </li>
                        <li href "about.php" style="text-align:center;" class="nav-li hvr-bounce-to-top">ABOUT US
                            <img src="img/navhover.png" style="position: absolute;z-index: 100;right: -19px;top: -1px;display: none" class="hrv-img" />
                        </li>
                        <li href "" style="text-align:center;" class="nav-li hvr-bounce-to-top">OUR GROUP
                            <img

I need to get the li attribute ("href") value using jquery.. but it alerts "undefined". Is there any other way to do this?

Upvotes: 1

Views: 867

Answers (3)

Nishit Maheta
Nishit Maheta

Reputation: 6031

No issue with your jquery code just update your href Attribute DEMO

NOTE : href attribut is not valid for li tag.

 href"about.php"
 href""

to

  href = "about.php"
  href = ""
  <li href = "about.php" style="text-align:center;" class="nav-li hvr-bounce-to-top">ABOUT US<img src="img/navhover.png" style="position: absolute;z-index: 100;right: -19px;top: -1px;display: none" class="hrv-img"/></li>

you need to add = after href attribute .

correct syntax of any attribute of tag is Attribute = "value"

Secod option

you can use data-* attribute instead of href .ex data-href="value"

DEMO

and update you jquery code

<li data-href = "about.php" style="text-align:center;" class="nav-li hvr-bounce-to-top">ABOUT US<img src="img/navhover.png" style="position: absolute;z-index: 100;right: -19px;top: -1px;display: none" class="hrv-img"/></li>


$(document).on('click','.nav-li',function(){
  alert( $(this).data("href") );
});

Upvotes: 4

Shaunak D
Shaunak D

Reputation: 20636

  1. href attribute on <li>s is invalid.

    Use data-* attributes.

    <li data-href="about.php">...</li>
    

    or next li contents inside an <a> anchor

    <li>
      <a href"about.php">
        ABOUT US
        <img/>
      </a>
    </li>
    
  2. It should be href="" - attribute="value"

Upvotes: 3

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

You can try using the following code

jQuery(".nav-li").click(function(event){
    var element = jQuery(event.currentTarget);
    var url = element.attr("href");
    alert(url);
});

Upvotes: 0

Related Questions