javascript - How to get value of selected dropdown value on button click in jquery - Stack Overflow

I am using Bootstrap with jquery to create a dynamic table consisting dropdown menu and button.I want

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".

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".

Share Improve this question asked Oct 17, 2018 at 7:12 RookieRookie 7555 gold badges12 silver badges31 bronze badges 4
  • 1 You are using list instead of <select>. You should use your script like this. $("#options .selected").text() – Sukanya Purushothaman Commented Oct 17, 2018 at 7:18
  • Maybe make it a <select> rather than a <ul>? – Jack Bashford Commented Oct 17, 2018 at 7:18
  • Possible duplicate of jQuery Get Selected Option From Dropdown – Jack Bashford Commented Oct 17, 2018 at 7:19
  • try $('#options').find('a[selected]').html() – Haidangdevhaui Commented Oct 17, 2018 at 7:45
Add a ment  | 

5 Answers 5

Reset to default 2

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())
});

May b you are looking for this. if it's dropdown

$('#update').click(function(){
 alert($('#options').find(":selected").text());
});

if its unordered list you can use this

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

Try this out:

$('#update').on('click', function () {
    alert($('#options').find('[selected]').html());
});

Firstly I made use of the on function, since the click function will trigger an actual click (IIRC).

Then I make use of the CSS selected [selected] which is the attribute selector; bined with find (which searches children for the selector), it should work.


All that said and done, there is no way of changing the selected attribute through clicking the on the dropdown - unless you use JavaScript - because only options use the selected attribute.

$('#options a').on('click', function () {
    $('#options a').removeAttr('selected');
    $(this).attr('selected', true);
});

The above code is a workaround that will allow your drop down to work correctly with my above code.
Effectively, all it is doing is removing the selected attribute from all #option a elements, and then gives it to the one that was clicked on.

JSFiddle
I used JSFiddle rather than a snippet for brevity, since this answer is already quite long as it is and prevents repeating the question askers code...

Your jquery search is not correct inside the click event. You are looking for option tag inside #option identifier and your html refers to a unordered list tag. Make selected element search according to your html

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

First, your for loop is duplicating element ids. The id attribute must be unique, otherwise any filtering operation, including attaching listeners, will return the first element only and your actions won't work. I've targeted a different selector in my example. You might get away with it by using duplicates in your dropdowns "options" as standins for value as long as you don't target them directly.

Then, since there are multiple rows, you'll have to find in which one the dropdown is so you can then get the corresponding value. You can do this by using closest and find.

Also, if you have many rows, you should consider using event delegation too, so you have less listeners attached. I've used this solution.

Now, since the dropdown isn't a real select, it won't respond to change events, so I provided my own selection function using delegates too. Since it's an anchor you can't use the :selected pseudoselector, you have to check for the attribute being present.

$('table').on('click', '.btn-update', function(evt) {
  $clicked = $(this).closest('tr').find('.dropdown-menu a[selected]')
  console.log($clicked.text())
  // You can get the emulated 'value' too
  console.log($clicked.attr('id'))
  // Cancel the 'button' default action
  evt.preventDefault()
});

$('table').on('click', '.dropdown-menu', function(evt) {
  // Find the 'selected' anchor inside this dropdown and remove the attribute
  $(evt.currentTarget).find('a[selected]').removeAttr('selected')
  // Add the attribute to the clicked one
  $(evt.target).attr('selected', true)
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered">
  <tbody>
    <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">
            <li><a id="weekly">Option 1</a></li>
            <li><a id="biweekly" selected>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 btn-update" id="update">
        </form>
      </td>
    </tr>
    <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">
            <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 btn-update" id="update">
        </form>
      </td>
    </tr>
  </tbody>
</table>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744279614a4566503.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信