问题:当我想返回熟练程度字段的值时,我总是得到一个空值。
期望结果将结果显示为索引页和我的sql数据库上选中的复选框的数组,例如[1,2],具体取决于选择的框数
这是我如何从我的索引模式中获取复选框字段输入的熟练度值的方法。
fetch(`{{ url('fetch/proficiency/list') }}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then(r => {
return r.json();
}).then(results => {
//console.log(results);
$("#all-proficiency").html("");
$("#edit-all-proficiency").html("");
$.each(results, function(index, val) {
$("#all-proficiency").append(`
<input type="checkbox" class="form-check-input" name="proficiency[]" value="${val.id}">${val.name}<br>
`);
$("#edit-all-proficiency").append(`
<input type="checkbox" class="form-check-input" name="proficiency[]" value="${val.id}">${val.name}<br>
`);
});
}).catch(err => {
console.log(err);
})
}```
**the ajax saving the project**
`function saveNewProject() {
var _token = $('#token').val();
var title = $('#title').val();
var context = $('#context').val();
var description = $('#description').val();
var start_date = $('#start_date').val();
var project = $('#project').val();
var proficiency = [];
$.each($("input[name='proficiency']:checked"), function() {
proficiency.push($(this).val());
});
var details = $('#details').val();
$.ajax({
url: "add/project",
type: "POST",
data:{
"_token": "{{ csrf_token() }}",
title:title,
context:context,
description:description,
start_date:start_date,
project:project,
stack:stack,
proficiency:proficiency,
details:details,`
**my project model where i fetch the proficiency from...**
```public function getProficiencyList(){
// body
$proficiency = [
[
"id" => 1,
"name" => "Expert"
],
[
"id" => 2,
"name" => "Intermediate"
],
[
"id" => 3,
"name" => "Beginner"
],
[
"id" => 4,
"name" => "Novice"
],
];
// return
return $proficiency;
}
您的复选框选择器不正确。只需替换:
$("input[name='proficiency']:checked")
带有此:
$("input[name='proficiency[]']:checked")
这是由于以下事实:复选框的name
属性实际上是name="proficiency[]"
,而不仅仅是name="proficiency"
Demo:
$('button').click(function() {
var proficiency = [];
$.each($("input[name='proficiency[]']:checked"), function() {
proficiency.push($(this).val());
});
console.clear();
console.log(proficiency)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="form-check-input" name="proficiency[]" value="1">1<br>
<input type="checkbox" class="form-check-input" name="proficiency[]" value="2">2<br>
<input type="checkbox" class="form-check-input" name="proficiency[]" value="3">3<br>
<input type="checkbox" class="form-check-input" name="proficiency[]" value="4">4<br>
<button>Save</button>