单选按钮检查javascript - 没有jquery

时间:2015-05-14 08:41:32

标签: javascript button radio checked

以下功能似乎无法正常工作..

function myCalculator () {

    var operator = document.getElementsByName("operator");
    var output = document.getElementById("output");
    var firstDig = parseInt(document.getElementById("firstDig").value);
    var secondDig = parseInt(document.getElementById("secondDig").value);   

    for (var i=0; i<operator.length; i++){

        var currentOperator = operator[i].id;

        if(currentOperator.checked == "Add"){
            var add = firstDig + secondDig;
                output = add;
        };


    };

        }

不知何故,“if”参数返回false但是,我得到了检查属性的元素...我正在制作一个简单的计算器...下面是html ......

<fieldset>

    <label>Enter Number:</label>
    <input type="text" id="firstDig" />
    <input type="text" id="secondDig" />
        <br/> <br/>
    <label>Select Operator:</label>
    <br/><br />

    <input type="radio" id="Add" name="operator" checked="checked" />
        <label for = "Add">Add</label>

    <input type="radio" id="Subt" name="operator" />
        <label for = "Subt">Subtract</label>

    <input type="radio" id="Divi" name="operator" />
        <label for = "Divi">Divide</label>

    <input type="radio" id="Multi" name="operator" />
        <label for = "Multi">Multiply</label>

</fieldset>


<fieldset>
    <p>RESULT</p>
    <input type="text" id="output" />
    <button type="button" onclick="myCalculator()">Calculate</button>
</fieldset>

即时通讯仍在学习javascript的基础所以我现在不是对jquery不感兴趣...所有答案都表示赞赏...谢谢

4 个答案:

答案 0 :(得分:3)

checked属性的值为true / false,因此您需要获取已检查的无线电,然后查看其ID是否为Add(您没有将值分配给无线电元素他们有id)。

以同样的方式output是输入元素,因此您需要指定其值

function myCalculator() {

    var operator = document.getElementsByName("operator");
    var output = document.getElementById("output");
    var firstDig = parseInt(document.getElementById("firstDig").value);
    var secondDig = parseInt(document.getElementById("secondDig").value);

    for (var i = 0; i < operator.length; i++) {

        var currentOperator = operator[i],
            result = '';

        if (currentOperator.checked) {
            if (currentOperator.id == "Add") {
                result = firstDig + secondDig;
            } else if (currentOperator.id == "Subt") {
                result = firstDig - secondDig;
            }
            output.value = result;
        };


    };

}

答案 1 :(得分:1)

if(currentOperator.checked == "Add"){..

错了。它只能有2个值truefalse。你可以检查它:

if(currentOperator == "Add" && operator[i].checked){..

另外output = add;

shud be

 output.value = add;

答案 2 :(得分:0)

变化 output = add; 至 output.value = add;

答案 3 :(得分:0)

for (var i=0; i<operand.length; i++){
var currentOperand = operand[i];
if (currentOperand.checked && currentOperand.id == "Add") {
var add = firstDig + secondDig;
output.value = add;
}else if (currentOperand,checked && currentOperand.id == "Subt"){
var subt = firstDig - secondDig;
output.value = subt;
};

我已将if语句扩展为else if,并且它已停止工作...以为我有了它