Omar
Omar

Reputation: 806

Get ID of LI element not working when in function in Jquery

I can grab the ID of the LI element using JQuery's click function, but when I make my own function the ID of the LI element comes up undefined:

http://codepen.io/omarel/pen/gwvpvQ

The first LI element uses Jquery's click function. The second element uses it's own function where the ID comes up undefined.

HTML

 <ul id="pricerange_options" class=" options">

    <li id="option1" data-value="1" class="dropdown-option">1</li>

    <li id="option2" data-value="1" class="dropdown-option" onClick="chooseDropDownOption();">2</li>

 </ul>

JQuery

  function chooseDropDownOption() {
        alert($(this).attr('id'));
    }

  $('#pricerange_options li').click(function () {
        alert($(this).attr('id'));
   });

Upvotes: 1

Views: 278

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337733

When you attach an unobtrusive event handler in jQuery the function runs under the scope of the element that raised the event, therefore the this keyword refers to the element.

When attaching an event through an on* event attribute it runs under the scope of the window, hence this refers to the window. To fix the problem, send the element as a parameter to your function:

function chooseDropDownOption(el) {
  alert($(el).attr('id')); // or just el.id
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="pricerange_options" class=" options">
  <li id="option2" data-value="1" class="dropdown-option" onClick="chooseDropDownOption(this);">2</li>
</ul>

It should be noted though that using on* event handlers is very outdated. You should always use unobtrusive event handlers where possible.

Upvotes: 4

Related Questions