Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's how you can do it:</p> <ol> <li><p>Bind the change event of the select element using <a href="http://api.jquery.com/change/" rel="nofollow">.change(handler)</a>. "handler" is a function that will be called when a change event is fired.</p></li> <li><p>Get the selected option element using the <a href="http://api.jquery.com/selected-selector/" rel="nofollow">:selected</a> selector.</p></li> <li><p>when using <a href="http://api.jquery.com/index/" rel="nofollow">.index()</a> without parameter, it returns the index of the matched element relatively to its siblings. So as you get the option element that is selected, it will return its index relatively to the other option elements. This implies of course your options are sorted. the returned index is zero-based.</p></li> <li><p>Set the value of the hidden field with <a href="http://api.jquery.com/val/" rel="nofollow">.val()</a>.</p></li> <li><p>To directly apply the change when an option is preselected, trigger the change event with <a href="http://api.jquery.com/change/" rel="nofollow">.change()</a> (no parameters).</p></li> </ol> <p>Here's the code:</p> <pre><code>var $select = $('#SomethingID'), $hidden = $('#myhidden'); $select.change(function(e) { var idx = $select.find('option:selected').index() + 1; $hidden.va('Opt' + idx); }).change();​ </code></pre> <p><strong><a href="http://jsfiddle.net/didierg/ujLkC/" rel="nofollow">DEMO</a></strong></p> <hr> <p>So if the actual value to set in the hidden field is not based on the index of the option element, but a random value, the best choice is to use data attribute. This way you can store the corresponding value to set on each option element:</p> <pre><code>&lt;select name="somethingName" id="SomethingID"&gt; &lt;option value="1" data-val="QBQ" selected="selected"&gt;Option #1&lt;/option&gt; &lt;option value="2ABC" data-val="ALA"&gt;Option #2&lt;/option&gt; &lt;option value="3ABC" data-val="OLP"&gt;Option #3&lt;/option&gt; &lt;/select&gt; </code></pre> <p>To get the value of the data attribute, use the <a href="http://api.jquery.com/data/" rel="nofollow">.data()</a> method:</p> <pre><code>var $select = $('#SomethingID'), $hidden = $('#myhidden'); $select.change(function(e) { var val = $select.find('option:selected').data('val'); $hidden.va(val); }).change();​ </code></pre> <p><strong><a href="http://jsfiddle.net/didierg/mvDH9/" rel="nofollow">DEMO</a></strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload