简体   繁体   中英

Jquery get selected text and value from selectlist optgroup

I need to get the selected text and value from the optGroup selectList below on the click of a button. So something like?

      $("#addButton").click(function () {

     var selected = ???
});          


  <select name="list">
    <optgroup label="mammals">
      <option>dog</option>
      <option>cat</option>
      <option>rabbit</option>
      <option>horse</option>
    </optgroup>
    <optgroup label="reptiles">
      <option>iguana</option>
      <option>snake</option>
    </optgroup>
  </select>

You can use Attribute Equals selector and val method.

$("#addButton").click(function() {
    // var selected = $('select[name="list"] :selected');
    var val = $('select[name="list"]').val();
});

val method return the value of selected option . However as your option tags have no value attributes, val returns the text of the selected option.

var value = $('select[name="list"] :selected').val();
var text  = $('select[name="list"] :selected').text();

http://jsfiddle.net/DRDsS/

Provide an id to your select like "list", and you can try this

$(function(){
   $("#addButton").click(function () {
       var select = $('select#list');
       var selectedItem= select.find(':selected');
       var selectedVal = select.val();
       var selectedText = selectedItem.text();
       var optgroupLabel = selectedItem.parent().prop('label');
       alert("val =" + selectedVal + " text ="+ selectedText+" group =" + optgroupLabel );
   });       
});

Check this DEMO

Hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM