选中多个复选框时更改按钮文本

时间:2019-05-22 16:09:33

标签: javascript

当选中2个或更多复选框时,有人可以帮助我更改按钮文本吗?

<input type="checkbox" name="test" id="test">     
<input type="checkbox" name="test1" id="test1"> 
<input type="checkbox" name="test2" id="test2">
<div class="compare-button"><span class="button">Text</span></div>

仅选中1个复选框时,应显示“文本”。选中2或3后,应说“已选中”。

谢谢!

1 个答案:

答案 0 :(得分:0)

编辑(之前错误地阅读了问题):我建议您对具有相同类的元素进行计数。像这样:

function changeText() {
    const inputElems = document.getElementsByClassName("check-class");
    let count = 0;

    for (let i=0; i<inputElems.length; i++) {       
        if (inputElems[i].checked === true){
            count++;
        }
    }

    const text = document.getElementById("text");
    if (count > 1) {
        text.innerText  = "Checked";
    } else {
        text.innerText  = "Text";
    }
}
<input type="checkbox" class="check-class" name="test" id="test" onchange="changeText();" />     
<input type="checkbox" class="check-class" name="test1" id="test1" onchange="changeText();" /> 
<input type="checkbox" class="check-class" name="test2" id="test2" onchange="changeText();" />

<span id="text">Text</span>