javascript - 根据选择表单将不同的值插入隐藏的输入字段

标签 javascript html forms

我需要根据从选择表单中选择的内容将值“折扣”插入到隐藏的输入字段中。如果选择选项 2、3 或 4,则应插入该值,如果选择 1,则隐藏的输入值留空。

我需要保留当前的选项值,因为它们也将被使用

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

最佳答案

实现这一目标的一种方法是使用以下脚本:

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

关于javascript - 根据选择表单将不同的值插入隐藏的输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56764464/

相关文章:

javascript - 简化方法以确保时间格式正确

php - 有没有办法在 gmail/wave/gdocs 中粘贴代码片段/ block ?

javascript - 如何为未知数量的复选框实现全选按钮

javascript - 使用 HTML 表单值进行 AJAX/PHP MySqli 查询

php - 多个选择输入的数组

javascript - AJAX请求与stripe结合

javascript - ReactJS + react 路由器 : How to disable link from React-Router's <Link>?

javascript - 为什么我想运行 Coffeescript cake 命令时却运行了 CakePHP 的 cake 命令?

javascript - 从 rangefilter 获取总和/总计

html垂直对齐输入类型按钮内的文本