简体   繁体   中英

how to get option id value using javascript

i want to get id value of option in select only using javascript.

<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>

I am already getting option value in calculate function now i also want to get value of quantity_to?> in a variable of calculate function

Store it as a data-* attribute instead of trying to parse it out of the option text.

<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();
}

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM