【问题标题】:Change input value according which option is selected根据选择的选项更改输入值
【发布时间】:2017-06-23 00:30:57
【问题描述】:

我想根据选择的选项更改input field 的值。 我做了这个功能,但它没有给我任何结果:

<script>

   function changeFunc() {
    var idpn = document.getElementById("idpn").value;       

    if(idpn.startsWith('v531')) {
       if(document.getElementById("price_type_chosen").options.selectedIndex = 2) {

            var ltvalue =document.getElementById("ltid").value=30;
        } else if (document.getElementById("price_type_chosen").options.selectedIndex = 3) {

            var ltvalue =document.getElementById("ltid").value=30;
         }

    } 
        alert('ok');
}

  </script>

你能告诉我函数的错误在哪里吗?

【问题讨论】:

  • 在 if 条件中使用 == 或 === 而不是 =

标签: javascript


【解决方案1】:

你不是在比较,你是在分配价值

if(document.getElementById("price_type_chosen").options.selectedIndex = 2) 

【讨论】:

  • 我更改了它,但始终相同的结果不要更改值 30。
  • 你可以记录值 document.getElementById("ltid").value 并检查它是否进入 if 条件,
  • 它返回数据库中存在的值。
【解决方案2】:

您需要在比较中使用==

<script>

       function changeFunc() {
        var idpn = document.getElementById("idpn").value;       

        if(idpn.startsWith('v531')) {
           if(document.getElementById("price_type_chosen").options.selectedIndex == 2) {

                var ltvalue =document.getElementById("ltid").value=30;
            } else if (document.getElementById("price_type_chosen").options.selectedIndex == 3) {

                var ltvalue =document.getElementById("ltid").value=30;
             }

        } 
            alert('ok');
    }

      </script>

【讨论】:

  • 谢谢你的回答,结果还是一样
  • 我不能做这个我应该定义什么是 ltvalue。
  • 当 if 语句满足时,你希望发生什么?
  • 将值 ltvalue 更改为 30。
  • 我不知道我问了这个问题
【解决方案3】:

if 语句中更改 2 个错误 比较(===)后,代码可以正常工作。

我还结合了if/else 语句,并将document.getElementById("price_type_chosen").options.selectedIndex 的值放入一个变量中以使其更具可读性。

function changeFunc() {
  var idpn = document.getElementById("idpn").value;

  if (idpn.startsWith('v531')) {
    var selectedIndex = document.getElementById("price_type_chosen").options.selectedIndex;

    //both values are in 1 'if statement' with an or operator
    if (selectedIndex == 2 || selectedIndex == 3) {
      var ltvalue = document.getElementById("ltid").value = 30;
    }
  }
  alert('ok');
}
price_type_chosen:
<select id="price_type_chosen">
  <option>0</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>
<br>

<label>idpn:</label><input id="idpn" type="text" value="v531" />
<br>
<label>ltid:</label><input id="ltid" type="text" value="" />
<br><br>
<button onclick="changeFunc()">changeFunc</button>

选择选项 2 或 3 将值 30 放入 #ltid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 2014-02-25
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多