我有一个可以打开进行编辑的表格。该表单是根据Ajax调用的结果填充的。 表单有六个复选框,我试图将其填充为“已选中”或“未选中”。
复选框; s:
<input class="days" type="checkbox" name="day0" id="Day0" value="0">
<input class="days" type="checkbox" name="day1" id="Day1" value="1">
<input class="days" type="checkbox" name="day2" id="Day2" value="2">
<input class="days" type="checkbox" name="day3" id="Day3" value="3">
<input class="days" type="checkbox" name="day4" id="Day4" value="4">
<input class="days" type="checkbox" name="day5" id="Day5" value="5">
<input class="days" type="checkbox" name="day6" id="Day6" value="6">
<input class="all" type="checkbox" name="Everyday" id="Everyday">
我需要的是,如果“ result [20]”的结果为0(这是天数),以使复选框处于选中状态(true),以此类推,则所有复选框都为此类
Ajax调用的结果是:
var day0 = result[20];
if(day0 == '0'){
$('#Day0').prop('checked', true);
} else {
$('#Day0').prop('checked', false);
}
var day1 = result[21];
if(day1 == '1'){
$('#Day1').prop('checked', true);
} else {
$('#Day1').prop('checked', false);
}
// and so on
在此先感谢您的帮助和时间。
答案 0 :(得分:1)
使用索引遍历数组。 if else也可以浓缩。在元素20处切片,让索引从0开始。
var result = ["11","April","DS1","Lobby","L","test_1920x1080.png","PNG","01-04-2019","00","00","30-04-2019","23","59","1920","1080","EXBHX","642652","6000","fade","600","","1","","3","","5",""];
result.slice(20).forEach(function(day, index) {
$('#Day' + index).prop('checked', day && day == index);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="days" type="checkbox" name="day0" id="Day0" value="0">
<input class="days" type="checkbox" name="day1" id="Day1" value="1">
<input class="days" type="checkbox" name="day2" id="Day2" value="2">
<input class="days" type="checkbox" name="day3" id="Day3" value="3">
<input class="days" type="checkbox" name="day4" id="Day4" value="4">
<input class="days" type="checkbox" name="day5" id="Day5" value="5">
<input class="days" type="checkbox" name="day6" id="Day6" value="6">