gpt4 book ai didi

javascript - 如何设置从数据表中的 Ajax 响应选中的复选框?

转载 作者:行者123 更新时间:2023-12-03 06:56:35 24 4
gpt4 key购买 nike

我这里有ajax响应代码,dataCompetence的值为2,5。我尝试在 comp_id 列中找到相同的 id,然后选中复选框。这是我的 html 代码:

<table id="competence_list" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="1%"><input name="select_all_competence" class="case" id="example-select-all-competence" type="checkbox"></th>
<th hidden>ID</th>
<th width="10%">Aspect</th>
<th width="40%">Description</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
if ($this->competenceList) {
foreach ($this->competenceList as $data) {
?>
<tr>
<td><input type="checkbox" name="idcheckbox_competence" id="idcheckbox_competence" class="case"></td>
<td hidden id="comp_id"><?php echo $data['competence_id']; ?></td>
<td><?php echo $data['aspect']; ?></td>
<td><?php echo $data['descriptions']; ?></td>
</tr>
<?php
$i++;
}
}
?>
</tbody>
</table>

这就是我尝试设置复选框选中的内容:

var dataCompetence = jsonData.dataCompetence;
if(jsonData.success){
$.gritter.removeAll();
$.each(dataCompetence.split(","), function(i,e){
$("#competence_list input[value='" + e + "']").prop("checked", true);
});

我不知道如何找到相同的值,然后将复选框设置为选中,请帮助我。谢谢

最佳答案

@Nike 请尝试按照以下步骤操作......

HTML

<div id="dvCheckBoxListControl"></div>

Jquery

<script>
$(document).ready(function () {
PopulateCheckBoxList();
})

function PopulateCheckBoxList() {
$.ajax({
type: "POST",
url: '@Url.Action("GetCheckBoxDetails", "Home")',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
//error: AjaxFailed
});
}

function AjaxSucceeded(result) {
BindCheckBoxList(result);
}
function BindCheckBoxList(result) {
CreateCheckBoxList(result);
}

function CreateCheckBoxList(checkboxlistItems) {
var table = $('<table></table>');
var counter = 0;
$(checkboxlistItems).each(function () {
table.append($('<tr></tr>').append($('<td></td>').append($('<input>').attr({
type: 'checkbox', name: 'chklistitem', value: this.Value, id: 'chklistitem' + counter, checked:this.IsSelected
})).append(
$('<label>').attr({
for: 'chklistitem' + counter++
}).text(this.Name))));
});

$('#dvCheckBoxListControl').append(table);
}

请在您的项目中创建一个模型 CheckBoxItem,如下所示..

型号

 public class CheckBoxItem
{
public string Name { get; set; }
public string Value { get; set; }
public bool IsSelected { get; set; }
}

Controller

 [HttpPost]
public ActionResult GetCheckBoxDetails()
{
List<CheckBoxItem> chkListAppointments = new List<CheckBoxItem>(){

new CheckBoxItem{ Value="1",Name="Jaipur", IsSelected=true},
new CheckBoxItem{ Value="2",Name="Ajmer",IsSelected=false},
new CheckBoxItem{ Value="3",Name="Sikar",IsSelected=true},
};
return Json(chkListAppointments, JsonRequestBehavior.AllowGet);
}

关于javascript - 如何设置从数据表中的 Ajax 响应选中的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com