[英]How to get the value of an option in a dropdown by knowing only the id of select tag using javascript
[英]how to get option id value using javascript
我想僅使用javascript獲取選擇中選項的ID值。
<select id="quantity" name="quantity" tabindex="2" onchange="calculate(this)" required autofocus>
<option value="">Choose Your Quantity</option>
<?php
if($prodqty)
{
foreach($prodqty as $qty)
{
?>
<option value="<?=$qty->discount?>"><?=$qty->quantity_from?> to <?=$qty->quantity_to?></option>
<?php } } ?>
</select>
我現在已經在calculate函數中獲取了選項值,我也想在calculate函數的變量中獲取quantity_to?>的值
將其存儲為data-*
屬性,而不是嘗試從選項文本中進行解析。
<option data-to="<?=$qty->quantity_to?>" value="<?=$qty->discount?>"><?=$qty->quantity_from?> to <?=$qty->quantity_to?></option>
JavaScript的:
function calculate(select){
var quantity_to = select.options[select.selectedIndex].getAttribute('data-to');
}
function calculate(elem) {
var value = elem.value;
var quantity = elem.querySelector('option[value="'+value+'"]').textContent.split(/to\s/).pop();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.