将2个不同的复选框中的2个参数传递给函数

时间:2011-03-15 03:02:35

标签: javascript html

<input type ="checkbox" id = "checkbox1" checked ="checked" value="1" onclick = "a()"/>
<input type ="checkbox" id = "checkbox1" checked ="checked" value="2" onclick = "a()"/>

function(checkbox1,checkbox2)
{ 
   if(checkbox1.checked == true && checkbox2.checked == false)
   {
     alert("checkbox1 is checked, Checkbox2 ix Unchecked");
   }
}

如何在()???

中传递checkbox1和checkbox2值

3 个答案:

答案 0 :(得分:2)

您可以使用以下方式抓住它:

var mycheckbox1 = document.getElementById('checkbox1');

var mycheckbox2 = document.getElementById('checkbox2');

您可能希望将checkbox2的id更改为id ='checkbox2',其中非唯一ID是无效语法。

如果您要求修改您发布的功能,则会出现以下情况:

<input type ="checkbox" id = "checkbox1" checked ="checked" value="1" onclick = "a()"/>
<input type ="checkbox" id = "checkbox2" checked ="checked" value="2" onclick = "a()"/>

function a(){
     var mycheckbox1 = document.getElementById('checkbox1');
     var mycheckbox2 = document.getElementById('checkbox2');
     if(mycheckbox1.checked && !checkbox2.checked)
          alert('checkbox1 is checked, checkbox2 is unchecked');
}

现在,如果您要求获取已选中复选框的值,则为以下内容:

<input type ="checkbox" id = "checkbox1" checked ="checked" value="1" onclick = "a(this)"/>
<input type ="checkbox" id = "checkbox2" checked ="checked" value="2" onclick = "a(this)"/>

function a(box){
    if(box.checked)
      alert(box.value);
}

答案 1 :(得分:0)

这是一个解决方案,它可以获取表单中的所有复选框并显示其值和状态

<form id="myForm">
<input type ="checkbox" id = "checkbox1" checked ="checked" value="1" onclick = "a()"/>
<input type ="checkbox" id = "checkbox2" checked ="checked" value="2" onclick = "a()"/>
</form>
<script>
function a(){
    form = document.getElementById("myForm")
    str = ""
for (i=0;i<form.elements.length;i++) {
    type = form.elements[i].type
     if (type=="checkbox") {
            str += "\n"
        str += (form.elements[i].checked)? form.elements[i].id + " is checked " : form.elements[i].id + " is unchecked ";
        str += "\n"
        str +=  form.elements[i].id + " value is  "+ form.elements[i].value;
     }


}
    alert(str);
}
</script>

如果您只想要个别值/州,请参阅下文 对于价值

 <input type ="checkbox" id = "checkbox1" checked ="checked" value="1" onclick = "a(this.value)"/>
    <input type ="checkbox" id = "checkbox1" checked ="checked" value="2" onclick = "a(this.value)"/>
    <script>
    function a(v){
        alert(v)
    }
    </script>

对于选中/未选中状态

<input type ="checkbox" id = "checkbox1" checked ="checked" value="1" onclick = "a(this.checked)"/>
<input type ="checkbox" id = "checkbox1" checked ="checked" value="2" onclick = "a(this.checked)"/>
<script>
function a(v){
    alert(v)
}
</script>

答案 2 :(得分:0)

我认为你 可以 这样做......如果 真的 想要

onclick="a(document.getElementById('checkbox1'), document.getElementById('checkbox2'))"
相关问题