[英]How to save multiple checkbox (jQuery and PHP)?
我想將多個復選框(PHP和JQuery)保存到MYSQL數據庫中。 示例表測試有4個字段。 A欄,NAME,C和D.
單擊保存后,它將保存到那些表中;
jQuery代碼:
$(document).ready(function() {
$("#btnsave").click(function() {
var test = [];
$("input[name='aa[]']:checked").each(function() {
test.push($(this).val());
});
alert(test);
});
});
function toggleCheckeda(status) {
$(".chkaa").each( function() {
$(this).attr("checked", status);
})
}
function toggleCheckedb(status) {
$(".chkab").each( function() {
$(this).attr("checked", status);
})
}
function toggleCheckedc(status) {
$(".chkac").each( function() {
$(this).attr("checked",status);
})
}
PHP代碼:
$db->Connect();
$stmt = $db->ExecData("select id,A,name,C,D from tbl_check");
<form id="frm1" name="frm1">
<table>
<tr>
<td>
<input type="checkbox" value="" onclick="toggleCheckeda(this.checked)">
</td>
<td></td>
<td>
<input type="checkbox" value="" onclick="toggleCheckedb(this.checked)">
</td>
<td>
<input type="checkbox" value="" onclick="toggleCheckedc(this.checked)">
</td>
</tr>
<tr>
<th>
A
</th>
<th>
Name
</th>
<th>
C
</th>
<th>
D
</th>
</tr>
<?php while ($row = $db->GetRow($stmt)){ ?>
<tr>
<td>
<input type="checkbox" class="chkaa" name="aa[]" id="chk[]" value="a<?php echo $row["id"]; ?>" />
</td>
<td>
<?php echo $row["name"]; ?>
</td>
<td>
<input type="checkbox" class="chkab" name="cc[]" id="chk[]" value="c<?php echo $row["id"]; ?>" />
</td>
<td>
<input type="checkbox" class="chkac" name="dd[]" id="chk[]" value="d<?php echo $row["id"]; ?>" />
</td>
</tr>
<?php } ?>
</table>
<input type="button" id="btnsave" name="btnsave" value="save" />
</form>
我不確定你的問題是什么,因為在標題中你說你需要通過jQuery和PHP保存多個復選框。 在您的PHP代碼中,您正在選擇它。 你做得太復雜了。 假設您想通過jQuery將復選框值保存到PHP。
你需要AJAX來通過jQuery保存復選框的值。 例如,請參閱下面的html表單。
<form action="" method="post" id="save-something"/>
<input type="checkbox" name="id[]" value="1"/>One
<input type="checkbox" name="id[]" value="2"/>Two
<input type="checkbox" name="id[]" value="3"/>Three
<input type="checkbox" name="id[]" value="4"/>Four
<input type="checkbox" name="id[]" value="5"/>Five
<input type="checkbox" name="id[]" value="6"/>Six
<input type="checkbox" name="id[]" value="7"/>Seven
<button type="submit" name="save">Save</button>
</form>
這是jQuery代碼。
$('#save-something').click(function(e){
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
success: function(msg){
alert('Sucessfully Saved');
}
});
});
並且在process.php中你可以做類似的事情。
if(isset($_POST['submit'])) {
if(!empty($_POST['id'])) {
$query = 'Your Insert Query or PHP logic goes here';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.