简体   繁体   English

如何使用 if 语句从 select 标记中提取值? (Javascript)

[英]How do you use an if statement to extract a value from a select tag? (Javascript)

My first input box我的第一个输入框

<input type="number" id="number1">
<br>
<br>

My options我的选择

<input type="number" id="number1">
<select id="operation">  
<option value="add">Add</option>
<option value="subtract">Subtract</option>
</select>
<br>
<br>

My second input box我的第二个输入框

<input type="number" id="number2">
<br>
<br>

This is a button below这是下面的按钮

<button onclick="calculateNum()">Calculate</button>
<br>
<p id="result">This is your result....</p>
</select>
<script>
function calculateNum(){
var operation = document.getElementById("operation").value;

In the below code (if statements), do I have syntax errors of any kind?在下面的代码(if 语句)中,我是否有任何类型的语法错误?

if(operation == "add"){
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var result = parseInt(number1) + parseInt(number2);
document.getElementById("result").innerHTML = result;
}
else if(operation == "subtract"){
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var result = parseInt(number1) - parseInt(number2);
document.getElementById("result").innerHTML = result;
}
}
</script>

Try getting the index of selected option and selecting it from options like so:尝试获取所选选项的索引并从如下选项中选择它:

let selectField = document.getElementById('operation');
let operation = selectField.options[selectField.selectedIndex].value;
if (operation == "add") {
    // do something
}

You have many mistakes, such as:你有很多错误,例如:

  • You're defining 2 inputs with ids number1 and number2 but you refer to num1 and num2您正在定义 2 个 ID 为number1number2的输入,但您指的是num1num2

  • You declare num1 and num2 variables but you use number1 and number2 while parsing.您声明num1num2变量,但在解析时使用number1number2

  • You override the plain text in the result object.您覆盖结果 object 中的纯文本。

I've edited your code.我已经编辑了你的代码。 Now you can try it as:现在您可以尝试如下:

 function calculateNum() { var operation = document.getElementById("operation").value; var num1 = document.getElementById("number1").value; var num2 = document.getElementById("number2").value; var result; if(operation == "add"){ result = parseInt(num1) + parseInt(num2); } else { result = parseInt(num1) - parseInt(num2); } document.getElementById("result").innerHTML = result; // or // document.getElementById("result").textContent = result; // document.getElementById("result").innerText = result; }
 <input type="number" id="number1"> <input type="number" id="number2"> <select id="operation"> <option value="add">Add</option> <option value="subtract">Subtract</option> </select> <button onclick="calculateNum()">Calculate</button> <br> <p>This is your result: <span id="result"></span></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM