我正在尝试创建一个函数来检查此行是否生成了任何复选框
foreach ($order->get_items() as $item ){
echo "<input type='checkbox' name='productinfo[]' value='" .$item->get_name() . "|" . $item->get_quantity() . "|" . $item->get_total() ."'>";
已检查,如果没有显示错误,则如何使用php / javascript制作一个?还是您需要jQuery做一个。最好,如果未选中任何一项,则将阻止完成表单提交
答案 0 :(得分:1)
这可以解决问题。检查名称为productinfo []“的输入元素的长度。已选中。在javascript中,数字0
为false。所有其他元素为true。
函数console.error()
将错误记录到控制台。但是您可以将其更改为任何您喜欢的错误消息。
function checkBoxCheck(e) {
if ($('input[name="productinfo[]"]:checked').length) {
console.log("at least one checked");
return true;
} else {
console.error("no checkbox checked");
return false;
}
}
$('#myForm').on('submit', checkBoxCheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="/dummy.html">
<input type='checkbox' name='productinfo[]' value='1'>
<input type='checkbox' name='productinfo[]' value='2'>
<input type='checkbox' name='productinfo[]' value='3'>
<input type='checkbox' name='productinfo[]' value='4'>
<input value="Check" type=submit>
</form>
答案 1 :(得分:0)
您可以使用jQuery的length
来选中至少一个复选框
if($('input[type="checkbox"]:checked').length > 0){
//your code here
}else{
alert('Please check atleast one checkbox');
}
注意:,这将检查页面上的所有复选框,因为您的输入复选框没有类别。
答案 2 :(得分:0)
要检查是否已选中复选框,请使用Jquery / Javascript中的checked
属性,如下所示:
jQuery:
var isChecked = $('input:checkbox').is(':checked'); // to check if any checkbox is checked
var isChecked = $('input[type=checkbox]:checked').length; // finds how many checkboxes are checked
if(length > 0){
alert(length); //alert how many checkboxes are checked
}
Javascript:
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
}
}
alert(count)
或者您也可以使用:s
var length=document.querySelectorAll('input[type="checkbox"]:checked').length
在提交按钮上为功能设置onclick
触发器。将按钮的类型从submit
更改为button
。
<button type ="button" id = "some-id" onclick = "savebutton();">
在Javascript函数内部使用验证:
function savebutton(){
if(document.querySelectorAll('input[type="checkbox"]:checked').length == 0){
alert('None of the checkboxes are checked');
}else{
var some_value = document.getElementById('id_of_some_element_you_wish_to_save').value;
$.ajax({
url : 'backend.php',
method : 'POST',
data: {values_you_want_to_send:some_value},
dataType: 'json',
success:function(data) {
window.reload();
}
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
}