What I am interested in getting is $option_value[‘price’] in a string from the dropdown, not . Using .value returns the later.
I have select menus that are created in a foreach() loop. The drop downs will hold price options. I am trying to give each product it’s own id so I can use the javascript onChange() function to update prices on the screen.
The select tag looks like this:
<select name="option[<?php echo $option['product_option_id']; ?>]" class="select_options" id="select_<?php echo $product['product_id']; ?>" onchange="getIt(this);">
and the javascript:
function getIt(el) {
var id = el.id;
a = document.getElementById(id).text;
alert(a);
}
Alerting out id gives me select_some number. So I can see that it is getting the id. but alerting out a gives me [object HTMLSelectElement].
so I tried
alert(a.options.selectedIndex.value);
and get unidentified.
<?php if ($product['options']) { ?>
<div class="options" id="option_<?php echo $product['product_id']; ?>">
<?php foreach ($product['options'] as $option) { ?>
<?php if ($option['type'] == 'select') { ?>
<div id="option-<?php echo $option['product_option_id']; ?>" class="option select_option">
<select name="option[<?php echo $option['product_option_id']; ?>]" class="select_options" id="select_<?php echo $product['product_id']; ?>" onchange="getIt(this);">
<option value=""><?php echo $text_select; ?></option>
<?php foreach ($option['option_value'] as $option_value) { ?>
<option value="<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
<?php if ($option_value['price']) { ?>
(<?php echo $option_value['price_prefix']; ?><span id="newPrice"><?php echo str_replace('.00','.',$option_value['price']); ?></span>)
<?php } ?>
</option>
<?php } ?>
</select>
</div>
<?php } ?>
I think this is what you are looking for:
el.selectedIndexgives you, obviously, the index of the currently selected option, which you can use as an index into the collection of options,el.options, and then get that option’stext. Thetextproperty belongs to each option, not to the select.Demo: http://jsfiddle.net/FCnUQ/
(Note that if no option is selected
selectedIndexwill be-1.)You don’t need to use
getElementById()at all because you already have a reference to the element,el.