1

I'm currently don't know how to get the value of the class like the code i'm posting below. If i click the li class that has value of 0 i want it to do A If i click the li class that has value of 1 i want it to do B

I'm using bootstrap and jquery/javascript.
Sorry if my code seems not tidy, this is my first post , i'll try to tidy it up in the next posts. 


I've been doing inspect elements and it's showed me no error, but the variable X isn't getting it's value from li.

Here it is i wanted it to do A if the selected is value 0

$(".clDropdown").click(function() {
    debugger ;var x = document.getElementsByClassName("clDropdown").selectedIndex;
    if (x == 0) {
        alert("DO A");
        debugger ;
    } else if (x == 1) {
        alert("DO B");
        debugger ;
    }
});
 <div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
        More <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">//if 0 do A
        <li class="clDropdown" value="0"><a href="#">Edit</a></li>
        <li class="clDropdown" value="1"><a href="#">Delete</a></li>
    </ul>
</div>
I expect that if i click the li that value 0 it'll do A , and if i click the li that has value 1 it'll do B
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
PiPio
  • 89
  • 1
  • 3
  • 11
  • [selectedIndex](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex) is for ` – Patrick Evans Jul 06 '19 at 20:34

1 Answers1

1
  • If you want to get index you can use $(this).index()

  • I prefer to use data attribute and get data with $(this).data('value')

$(".clDropdown").click(function() {
  debugger;
  var x = $(this).data('value');
  if (x == 0) {
    alert("DO A");
    debugger;
  } else if (x == 1) {
    alert("DO B");
    debugger;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
    More <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">//if 0 do A
    <li class="clDropdown" data-value="0"><a href="#">Edit</a></li>
    <li class="clDropdown" data-value="1"><a href="#">Delete</a></li>
  </ul>
</div>
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28