简体   繁体   中英

Get 2 values from ONE selectbox (optgroup and option selected) with jQuery

Can somebody help me with this, I have a selectbox that looks like this:

<select name="scatid">
<optgroup label="June">
  <option>2005</option>
  <option>2006</option>
  <option>2007</option>
  <option>2008</option>
</optgroup>
<optgroup label="July">
  <option>2005</option>
  <option>2006</option>
</optgroup>

and I also have an empty inputbox...

What I'm trying to achieve is, if for example I select from the selectbox year 2008 (June optgroup)... the inputbox value get's automaticaly the text "June 2008" (optgroup name + option selected)... etc etc..

Can somebody give me an example how can I achieve this? Thank you very much

Just use value attributes to give the value you want.

<select name="scatid">
<optgroup label="June">
  <option value="June 2005">2005</option>

附带条件,您实际上并不想这样做:

$("#scatid").find("option:selected").parent().attr('label')

You can get the label by reading label property of the optgroup element:

$('select[name="scatid"]').on('change', function(){
   var label = this.options[this.selectedIndex].parentNode.label;
   $('input[type=text]').val(label + ' ' + this.value);
});

http://jsfiddle.net/uEFx3/

Try this using JQuery:

$(function(){
$('select[name="scatid"]').change(function(){
    alert($(this).find('option:selected').parent('optgroup').attr('label')+'  '+$(this).val());
});
});

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