我正在使用以下代碼位來確保至少有一個複選框被選中,它會將複選框的「值」輸出到名爲「cont」的ID。我正在尋找一種方法將輸出轉換爲數組(PHP)。我對JS不太擅長。複選框值爲php數組
<?php
$count = '0';
while($count <= '2') {
$count++;
$the_name = "chkBx";
$the_value = 'checkbox'.$count;
if ($count == '1') {
$its_checked = 'checked';
} else {
$its_checked = '';
}
?>
<input type="checkbox" name="<?php echo $the_name; ?>" value="<?php echo $the_value; ?>" <?php echo $its_checked; ?> >
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="cont"></div><!-- OUTPUTS HERE-->
<script>
$('input[type="checkbox"][name="<?php echo $the_name; ?>"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="<?php echo $the_name; ?>"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#cont').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#cont').html("At least one value must be checked!");
return false;
};
});
</script>
#
更新,仍然遇到了麻煩,從打勾到一個PHP變量的複選框的值,這裏是我現在有:
<?php
$the_name = "myCheck";
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
1.<input type="checkbox" class="<?php echo $the_name; ?>" name="the_name" value="1" checked>
2.<input type="checkbox" class="<?php echo $the_name; ?>" name="the_name" value="2">
3.<input type="checkbox" class="<?php echo $the_name; ?>" name="the_name" value="3"><br/>
<span class="cont" name="bob" value="9999"></span>
<script>
function checkIt() {
var getArrVal = $(".myCheck:checked").map(function() {
return this.value;
}).get();
if (getArrVal.length) {
$('.cont').html(getArrVal.join(","));
var x=$(".cont").text();
var variablename = $(".cont").val();
} else {
$('.cont').html("At least one value must be checked!");
$(this).prop("checked", true);
getArrVal=[$(this).val()];
return false;
}
console.log(getArrVal);
}
$(function() {
$(".myCheck").on('click',checkIt);
checkIt();
});
</script>
你需要什麼數組?同樣地圖返回一個數組 – mplungjan
您可能想要使用AJAX將輸出發送到PHP,或者可能我沒有理解您的問題 – Ahmad