Search code examples
javascripthtmldrop-down-menuactionlistener

Is it possible to have an action listener on a list item element and pass it as a parameter in JavaScript?


Is it possible to set an action listener for a list item in HTML and pass what the user clicked in JavaScript?

Index.html:

<div class="dropdown">
<button class="btn d-flex align-items-center" type="button">
    <h3 class="fs-1 fw-bold">Set Limit</h3>
</button>
<ul class="dropdown-menu">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
</div>

<script>
$(function() {

   // I want this to be able to get its value
   // depending on what the user clicked from the <li> tag
   var limit = 1;
});
</script>

I updated my code now to

Index.html:

<select id="dropdown">
   <option value="A" data-number="1">option1</option>
   <option value="B" data-number="2">option2</option>
   <option value="C" data-number="3">option3</option>
   <option value="D" data-number="4">option4</option>
</select>

<script>
$('#dropdown').change(function(){
   var number = $(this).find('option:selected').attr('data-number');
});

$(function() {
   /* I am unsure now on how to get the number variable from above and put it here in my var limit */
   var limit = ;
});

</script>

Solution

  • I guess it really depends on your flow of data. Here I'm grabbing the selected value from the select element within the change handler, and passing it as an argument to a function called main which logs it to the console.

    Note: I moved the value from the data-number attribute to the value (otherwise what's the point of the value...?)

    $('select').on('change', handleChange);
    
    function handleChange() {
      const limit = $(this).val();
      main(limit);
    }
    
    function main(limit) {
      console.log(limit);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    <select class="form-select">
      <option selected disabled>Select an option</option>
      <option value="1">option1</option>
      <option value="2">option2</option>
      <option value="3">option3</option>
      <option value="4">option4</option>
    </select>