I'm using a <select></select>
dropdown and I want to change the value of the div #price
, however I need to use the value selector to send the data to another form. My question is can i use two options in the value=""
or is it possible to use another selector such as the data=""
below?
<select id="choose">
<option value="test1" data="4.00">Test1</option>
<option value="test2" data="6.00">Test2</option>
<option value="test3" data="7.00">Test3</option>
</select>
<div id="price"></div>
The jQuery below only returns test1 test2 etc, how do i return a custom data value?
<script type="text/javascript">
jQuery('#choose').change(function(event) {
jQuery('#price').html(jQuery('#choose').val());
});
</script>
Thanks you for your help.
You can find the selected option element using the :selected selector and then get the value of the data attribute
jQuery('#choose').change(function (event) {
jQuery('#price').html(jQuery('#choose option:selected').attr('data'));
}).change(); //to iniitize the value on load
Demo: Fiddle
But it will be better to use a data-* attribute
<select id="choose">
<option value="test1" data-value="4.00">Test1</option>
<option value="test2" data-value="6.00">Test2</option>
<option value="test3" data-value="7.00">Test3</option>
</select>
<div id="price"></div>
then
jQuery('#choose').change(function (event) {
jQuery('#price').html(jQuery('#choose option:selected').data('value'));
}).change();
Demo: Fiddle