onclick()函数用于多个复选框选择

时间:2014-07-01 18:00:38

标签: javascript php

我需要一种可以获得多个复选框选项的方法,我知道有一个onclick事件,我可以通过它来做,但这只是单个复选框。谢谢你的建议

4 个答案:

答案 0 :(得分:1)

这是我的代码,它给出了一个带有多个复选框id的数组。您可以根据您的要求使用该数组。在您的机器中运行它将获得清晰的概念

 <script type="text/javascript" language="javascript">
        var arr = new Array();
        function createArr(id){
            var chkBoxId =  document.getElementById("arr_"+id);

            if(chkBoxId.checked){
                arr.push(chkBoxId.value);
            } else{
                for(var i = arr.length - 1; i >= 0; i--) {
                    if(arr[i] === chkBoxId.value) {
                       arr.splice(i, 1);
                    }
                }
            }
            alert(arr); // here you will get your array with multiple checkbox Id and you can use it
        }
    </script>
    <form name="CreateArray" id="CreateArray" method="post">
    <?php
        for($i=1;$i<=10;$i++){
    ?>
    <?php echo $i.".";?>&nbsp;<input type="checkbox" name="arr[]" value="<?php echo $i?>" id="arr_<?php echo $i?>" onclick="createArr(<?php echo $i?>);"/>
    <?php
        }
    ?>
    </form>

答案 1 :(得分:0)

使用jQuery:

$('.select-all').click(function(e) {
            e.preventDefault();
            CheckAll();
    });

function CheckAll() {
    $("#checkboxes input").each( function() {
        $(this).attr("checked",status);
    });
}

HTML:

<p><a href="#" class="select-all">Select All</a></p>


<div id="checkboxes">
<p><input type="checkbox" name="vehicle" value="1" /> Hijo de Satan</p>
<p><input type="checkbox" name="vehicle" value="1" /> Hijo de Satan</p>
<p><input type="checkbox" name="vehicle" value="1" /> Hijo de Satan</p>
<p><input type="checkbox" name="vehicle" value="1" /> Hijo de Satan</p>
<p><input type="checkbox" name="vehicle" value="1" /> Hijo de Satan</p>
</div>

检查此示例:

http://examples.arturito.net/jquery/selectall/

答案 2 :(得分:0)

使用像jQuery这样的框架的最简单的方法,基本上你有3个选项,无论你使用哪个选项,你都可以使用“:checkbox”作为下面的示例,只需记住.live将附加即使你动态添加新的checbox,也会发生事件。

。点击

$( "#YourCheckBoxID" ).click(function() {
  alert( "User clicked on Checkbox" );
});

.bind

$( "#YourCheckboxID" ).bind( "click", function() {
  alert( "User clicked on Checkbox" );
});

.live

$(":checkbox").live('click', function() {
    alert('User clicked on Checkbox');
});

问候。

答案 3 :(得分:0)

<强> HTML

<form action="url" method="post" id="form">
    <input type="checkbox" name="box" id="box1" value="checkVal1" />
    <input type="checkbox" name="box" id="box2" value="checkVal2" />
    <input type="submit" name="submit" id="submit" value="Submit" />
</form>

<强> JQUERY

$(document).ready(function(){
    $("#submit").click(function(){
        var value = $("input[type='checkbox']").val();
        console.log(value);
    })
})

这应该有用。

相关问题