简体   繁体   中英

Change value of select option based on checkbox

Is there is way to change the value of select option if user check the check box. If user select "four" from select option, its default value is "4".Now if user check the checkbox, select option value becomes "44".

<select name="sel" id="MySelect">
<option value="">Select One</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
</select>

<input type="checkbox" name="btn_radio" />Discount

Just modify the <option> when the checkbox changes:

 (function() { var discount = document.getElementById("discount"); var option = document.querySelector("#amount option[value='4']"); discount.addEventListener("change", function(e) { if (this.checked) { option.value = 44; option.textContent = "Fourty-Four"; } else { option.value = 4; option.textContent = "Four"; } console.log("value: %s, text: %s", option.value, option.textContent); }); })(); 
 <select id="amount"> <option value="">Select One</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> </select> <label><input type="checkbox" id="discount" />Discount</label> 

See also: document. getElementById() document. getElementById() , document. querySelector() document. querySelector() , and EventTarget. addEventListener() EventTarget. addEventListener()

if I understand you correctly, and if you can use jQuery it should be possible.

Since you need to have option with value "44" you need to add/remove this option dynamically, when user check/uncheck checkbox.

I prepared simple example, it should be helpful for you:

https://jsfiddle.net/qv9nxhov/

$('select').on('change', function() {
    //show current value
    $('.result').text($(this).val());

    //remove discount when choose other option
    $('select option[value="44"]').remove();
    $('input').attr('checked', false);
});

$('input').on('click', function() {
    //check if checkox is checked    
    if ($(this).is(':checked')) {
        //add extra option
        $('select').append('<option value="44" selected="selected">Discount</option>');
    } else {
        //remove extra option
        $('select option[value="44"]').remove();
    }
    //show current value
    $('.result').text($('select').val());
});

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