Javascript比较字符串不起作用

时间:2017-11-16 08:19:14

标签: javascript html

我需要比较字符串,因为我需要进行计算。 HTML中select选项的字符串和另一个字符串将是变量字符串。

这是我的HTML代码:

 <label>Freight Cost Mode</label>
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">  
 <option>Percentage</option>
 <option>Monetary</option>
 </select> 
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">

这是我的javascript代码:

        <script>
        function val() {
        var input = document.getElementById("freightcostmode_insert").value;
        var calculation = document.getElementById("freightCost_insert").value;
        if(inputing == "Percentage"){
            document.getElementById('freight').value = calculation*1.5;
        }if else(inputing == 'Monetary'){

        }         

        }
        </script>

2 个答案:

答案 0 :(得分:1)

首先,您的inputing变量不存在 - 也许input

第二次将calculation值解析为数字。

您的代码中也有一些语法错误。

&#13;
&#13;
function val() {
  var input =  document.getElementById("freightcostmode_insert").value;
  var calculation = document.getElementById("freightcost_insert").value;
  
  if(input == "Percentage"){
     document.getElementById('freight').value = parseInt(calculation) * 1.5;
  } else if(input == 'Monetary'){

  }         
}
&#13;
<label>Freight Cost Mode</label>
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">  
 <option>Percentage</option>
 <option>Monetary</option>
 </select> 
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

工作代码

&#13;
&#13;
function val() {
  var input = document.getElementById("freightcostmode_insert").value,
    calculation = document.getElementById("freightcost_insert").value

  document.getElementById('freight').value = input === "Percentage" ?
    calculation * 1.5 : calculation * 2.5;
}
&#13;
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">  
   <option>Percentage</option>
   <option>Monetary</option>
 
 </select>

<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">
&#13;
&#13;
&#13;