Insert different value into hidden input field based on select form

Viewed 515

I need to have the value "discount" inserted into a hidden input field based on what is chosen from a select form. If options 2, 3 or 4 are selected then the value should be inserted, if 1 is selected then the hidden input value is left empty.

I need to keep the current option values as they will also be used

<div class="form-group">
    <div class="form-inline">
      <select id="myselect" name="quantity">
        <option value="1" selected="selected">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
      <input type='hidden' id='myhidden' value=''>
    </div>
</div>
1 Answers

One way to achieve that would be with the following script:

/* Attach a "change" event listener where the value of "myhidden" 
will be updated based on the selected option in "myselect" */
document.getElementById('myselect').addEventListener('change', (event) => {

  /* Get the current value of "myselect" as well as the hidden element */
  const mySelectValue = event.currentTarget.value;
  const hiddenElement = document.getElementById('myhidden');

  if (mySelectValue === '1') {
    /* If value of "myselect" is 1 then clear value of hidden element */
    hiddenElement.value = '';
  } else {
    /* Otherwise assign the value of "discount" to the hidden element */
    hiddenElement.value = 'discount';
  }

  console.log(`hiddenElement.value updated to ${hiddenElement.value}`);
});
<div class="form-group">
  <div class="form-inline">
    <select id="myselect" name="quantity">
      <option value="1" selected="selected">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
    </select>
    <input type='hidden' id='myhidden' value=''>
  </div>
</div>

Related