【发布时间】:2019-04-12 18:17:43
【问题描述】:
正在处理一个带有复选框输入的表单。该表单有一个复选框输入字段,我根据是否选中复选框动态更改值。当用户单击复选框时,该值应更改为 1 ,,当未单击时,该值应为零。我正在通过 AJAX 收集值并提交到后端(在 PHP Laravel 中构建),当我 dd() 值时,我得到复选框的空值,请协助
包含复选框字段的布局
<div class="check-now {{ $errors->has('spouse') ? ' has-error' : '' }}" style="width: 100%;">
<h1 class="cover-travel">I am travelling with</h1>
<label class="spouse-me">
<h1 class="pumba">Spouse</h1>
<input type="checkbox" id="spouse" value="" class="spouse" onClick="checkMark()">
</label>
@if ($errors->has('spouse'))
<span class="help-block">
<strong>{{ $errors->first('spouse') }}</strong>
</span>
@endif
</div>
改变复选框值的函数
function checkMark() {
var checkBox = document.getElementById("spouse");
var text = document.getElementById("spouseDetail");
// If the checkbox is checked, display the output text
if (checkBox.checked == true){
checkBox.value = '1';
} else {
checkBox.value = 'O';
}
}
AJAX 向后端提交数据
// Get the form via its id
var form = $('#travel_form');
$( "form" ).submit(function( event ) {
event.preventDefault();
//alert('clicked');
//Fetch the value of spouse
var spouse = $('#spouse').val();
//Log in console tab am getting an empty value
console.log(spouse);
//Add in a JS object
var type = {
'spouse' : spouse
}
$.ajax({
type: "POST",
url: "getplans",
data:JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function(response){
window.location.href="getp" ;
},
//Alert errors from backend
error: function(data) {
var errors = '';
for(datos in data.responseJSON){
errors += data.responseJSON[datos] + '\n';
}
alert(errors);
}
});
});
控制器处理 AJAX 调用
public
function validatePlanEntries(Request $request)
{
//dd($request->all());
}
【问题讨论】:
-
无需更改复选框的值。发布表单时,如果未选中复选框,则不会提交。就像它不存在一样,复选框的值是无关紧要的。所以基本上,如果你在提交表单时得到了复选框,它就会被选中。
-
@MagnusEriksson 我理解你,问题是我真的需要那个复选框值,因为我发布到 API
-
function checkMark() { var checkBox = document.getElementById("spouse");警报(复选框); // 你在这里得到什么?
-
if (checkBox.checked == true){ checkBox.value = '1';警报(复选框); } else { checkBox.value = 'O';警报(复选框); }
-
@SayedMohdAli 使用 if 条件来检查复选框是否被选中,如果没有更改则将值更改为 1 默认为零