I can’t quite get my head around this idea, wonder if someone could help out please?
I have a form with 12 options, option ‘1’ is selected by default. There is a hidden field that is populated with corresponding values.
What I want to achieve is: When option 1 is selected, the value of the hidden text field updates to “Opt1”, and so on through to “Opt12”
I hope the following renders correctly as XHTML
The best way for me to explain if I may, is as follows
<select name="somethingName" id="SomethingID">
<option value="1" selected="selected">Option #1</option>
<option value="2ABC">Option #2</option>
<option value="3ABC">Option #3</option>
<option value="4ABC">Option #4</option>
<option value="5ABC">Option #5</option>
<option value="6ABC">Option #6</option>
<option value="7ABC">Option #7</option>
<option value="8ABC">Option #8</option>
<option value="9ABC">Option #9</option>
<option value="10ABC">Option #10</option>
<option value="11ABC">Option #11</option>
<option value="12ABC">Option #12</option>
</select>
<input type='hidden' id='myhidden' value=''>
If/When Option #1 is selected, the value of myHidden is equal to “Opt1”
If/When Option #2 is selected, the value of myHidden is equal to “Opt2”
and so on. I say if/when for the idea that the hidden text field is updated on select.
Can anyone please suggest how I would achieve this with Jquery?
Here’s how you can do it:
Bind the change event of the select element using .change(handler). “handler” is a function that will be called when a change event is fired.
Get the selected option element using the :selected selector.
when using .index() 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.
Set the value of the hidden field with .val().
To directly apply the change when an option is preselected, trigger the change event with .change() (no parameters).
Here’s the code:
DEMO
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:
To get the value of the data attribute, use the .data() method:
DEMO