user3107804 user3107804 - 7 months ago 32
HTML Question

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

Answer

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>

<!-- console visualization; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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