How to get value of selected dropdown value on button click in jquery

10,151

If you are using select from control then no worry to code for it. Just do a little change in your code.

$('#update').click(function(){
  alert($('#options').val());
});

Or if you are using ul, li then change your jquery code like this.

$('#update').click(function(){
  alert($('#options .selected').text())
});
Share:
10,151
Rookie
Author by

Rookie

An enthusiast Linux based mobile framework developer

Updated on June 04, 2022

Comments

  • Rookie
    Rookie almost 2 years

    I am using Bootstrap with jquery to create a dynamic table consisting dropdown menu and button. I want to get value of dropdown menu selected in jquery on button click.

    Below is my code

    <table class="table table-bordered">
      <tbody>
      {% for item in items %}
        <tr>
          <td>
            <div class="dropdown">
              <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Select
              </button>
              <ul class="dropdown-menu" role="menu" id="options" onchange="selectFromDropDown(this.value)">
                <li><a id="weekly" selected>Option 1</a></li>
                <li><a id="biweekly">Option 2</a></li>
                <li><a id="monthly">Option 3</a></li>
              </ul>
            </div>
          </td>
          <td>
            <form data-toggle="validator" role="form" >
              <input type="submit" value="Update" class="btn btn-xs btn-block" id="update">
            </form>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    

    And below is the jquery

    $('#update').click(function(){
      alert($('#options option:selected').html())
    });
    

    When I run above code it returns "undefined".

    • Sukanya Purushothaman
      Sukanya Purushothaman over 5 years
      You are using list instead of <select>. You should use your script like this. $("#options .selected").text()
    • Jack Bashford
      Jack Bashford over 5 years
      Maybe make it a <select> rather than a <ul>?
    • Jack Bashford
      Jack Bashford over 5 years
    • Haidangdevhaui
      Haidangdevhaui over 5 years
      try $('#options').find('a[selected]').html()