質問

In my html file I have this code :

        <div class="multiselect">
        <label><input type="checkbox" id="Field_1" name="Field_1" value="1" />something1</label>
        <label><input type="checkbox" id="Field_2" name="Field_2" value="2" />something2</label>
        <label><input type="checkbox" id="Field_3" name="Field_3" value="3" />something3</label>
        <label><input type="checkbox" id="Field_4" name="Field_4" value="4" />something4</label>
        <label><input type="checkbox" id="Field_5" name="Field_5" value="5" />something5</label>
        <label><input type="checkbox" id="Field_6" name="Field_6" value="6" />something6</label>
        </div>

        <button type="button" onClick="validateMyForm()">Send This form</button

And then in the JS code I do the following :

function validateMyForm(){

        // some code 

        // from here - the multibox 
        var val1 = $("#Field_1").val();
        var val2 = $("#Field_2").val();
        var val3 = $("#Field_3").val();
        var val4 = $("#Field_4").val();
        var val5 = $("#Field_5").val();
        var val6 = $("#Field_6").val();             

        // more

}

But even when I don't check one of the 6 options , I still get its original value , i.e. the variables

val1 -> 1
val2 -> 2
val3 -> 3
val4 -> 4
val5 -> 5
val6 -> 6

are always with the same value .

So , how can I know when the user checked or didn't check one of the options ?

Much appreciated

役に立ちましたか?

解決

Probably you're looking for $("#Field_1").is(':checked').

他のヒント

Try :

$( "#Field_1").prop( "checked" )

Will return True when checked

you can list the checkbox elements into an array and then use the for loop to loop through each element to alert if a box has been checked or not. i used document.getElementById for more visual clarity.

<script type="text/javascript">
<!--
function validateMyForm(){
    chexBx=new Array();
    chexBx[1]=document.getElementById("Field_1");
    chexBx[2]=document.getElementById("Field_2");
    chexBx[3]=document.getElementById("Field_3");
    chexBx[4]=document.getElementById("Field_4");
    chexBx[5]=document.getElementById("Field_5");
    chexBx[6]=document.getElementById("Field_6");

    for(i=1;i<=6;i++){
        if(chexBx[i].checked){
            x=chexBx[i].value;
            alert("box "+i+" was checked with the value of "+x);
        }
        if(!chexBx[i].checked){
            alert("box "+i+" was not checked");
        }
    } 
}
 -->
</script>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top