P. Lau
P. Lau

Reputation: 165

Put onClick event in <li> to call AJAX

When I put onClick event in button element inside li element like below to make AJAX:

<ul>
<li><button value="orange" onClick="qCat(value)">Orange</button></li> 
<li><button value="apple" onClick="qCat(value)">Apple</button></li>
</ul>

It works nicely.

But if I take away button to apply event directly to li element like below make AJAX:

<ul>
<li value="orange" onClick="qCat(value)">Orange</li> 
<li value="apple" onClick="qCat(value)">Apple</li>
</ul>

It won't work. Anything wrong with my code? Pls advice. Thanks.

Upvotes: 0

Views: 2520

Answers (5)

taha
taha

Reputation: 1017

The value attribute sets the value of a list item. The following list items will increment from that number.

The value must be a number and can only be used in ordered lists

In order to get the expected result use data-* (a HTML global attribute)

qCat = function(elm){
  val = elm.getAttribute('data-value');
  alert(val);
}
<ul>
  <li data-value="orange" onClick="qCat(this)">Orange</li> 
  <li data-value="apple" onClick="qCat(this)">Apple</li>
</ul>

Upvotes: 0

Lalit Sachdeva
Lalit Sachdeva

Reputation: 6619

Please have a look into this updated code.

function qCat(event){
debugger;
  console.log($(event.target).attr('value'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li value="orange" onClick="qCat(event)">Orange</li> 
<li value="apple" onClick="qCat(event)">Apple</li>
</ul>

Upvotes: 0

Ramin Ahmadi
Ramin Ahmadi

Reputation: 629

function First(){
        alert('it is the first option');
    }

    function Second(){
        alert('it is the second option');
    }
     function General(){
        alert('it is a shared option');
    }
<ul>
    <li><a href="#" onclick=First();>First option</a></li>
    <li><a href="#"onclick=Second();>Second option</a></li>
    <li><a href="#"onclick=General();>Third option</a></li>
    <li><a href="#"onclick=General();>Forth option</a></li>
</ul>     

Upvotes: 0

freginold
freginold

Reputation: 3956

You just need to change the argument passed to your function (thanks to @epascarello for pointing that out). See the code below.

function qCat(val) {
  console.log(val.getAttribute('value'));
}
<ul>
<li value="orange" onClick="qCat(this)">Orange</li> 
<li value="apple" onClick="qCat(this)">Apple</li>
</ul>

Upvotes: 1

Peter B
Peter B

Reputation: 24137

The value attribute of an li element is supposed to be a number.
Furthermore it is only supported for Ordered Lists (ol).

The values can even be auto-incrementing by setting the first value to e.g. 100 and then the rest will follow.

If I test your code then the function qCat() receives a 0 (zero) parameter which is consistent with the above.

For additional info see here: https://www.w3schools.com/tags/att_li_value.asp

Upvotes: 2

Related Questions