根据其他两个输入来更改文本字段的输入值

时间:2019-05-23 22:38:49

标签: javascript

从下拉菜单中选择“是”时,我想将数字输入中的值添加到第一个文本输入中。例如,如果在文本输入中添加了“ ABCD”,并且选择了“是”并且数字输入中为1,则文本输入将为ABCD-1。

   <input type="text" name="pr" id="pr" />
   <select  class="form-control" name ="rt" id="rt">
   <option value = "0" selected>No</option>
   <option value = "1">Yes</option>
   </select>
    <input type="number" name="at" id="at"/>

    <script>
    $('#pr, #rt, #at').change(function(){
    var pr1 = document.getElementById('#pr').value
    var rt1 = document.getElementById('#rt').value;
    var at1 = document.getElementById('#at').value;

    var rr = pr+at;

    if(rt1 == 1){
        $pr.value = rr;
    }else{
        $pr.value = pr1;
    }

    });
   </script>

1 个答案:

答案 0 :(得分:0)

const firstInput = document.getElementById('firstInput');
const secondInput = document.getElementById('secondInput');
const selectInput = document.getElementById('selectInput');

selectInput.addEventListener('change', e => {
  if(e.target.value == 1) {
    firstInput.value += '-' + secondInput.value;
  }
});
<input type="text" name="pr" id="firstInput" />
<br/>
<input type="number" name="at" id="secondInput"/><br/>

<select  class="form-control" name ="rt" id="selectInput">
  <option value = "0" selected>No</option>
  <option value = "1">Yes</option>
</select>

这是修改后的解决方案:

<input type="text" name="pr" id="firstInput" />
<br/>
<input type="number" name="at" id="secondInput"/><br/>

<select  class="form-control" name ="rt" id="selectInput">
  <option value = "0" selected>No</option>
  <option value = "1">Yes</option>
</select>

<script>
    const firstInput = document.getElementById('firstInput');
    const secondInput = document.getElementById('secondInput');
    const selectInput = document.getElementById('selectInput');

    selectInput.addEventListener('change', e => {
      if(e.target.value == 1) {
        firstInput.value += '-' + secondInput.value;
      }
    });
</script>

像魅力一样工作!这也是片段