我制作了两个自定义jquery函数,在选中复选框时获取数据数组。我试图将数组指定为输入字段的值(type = hidden)并将其发送到laravel控制器。问题是当我检查几个字段时,数组未正确填充。它只取一个值并将其发送给控制器。我需要将所有检查的值作为数组并将其发送到laravel控制器。请帮助我这方面。我粘贴了下面的东西:
jquery的:
<script>
var allvals = [] ;
function categoryDelete(){
$('.categorySelect:checked').each(function(){
allvals = $(this).val();
})
return allvals;
}
function subcategoryDelete(){
$('.subcategorySelect:checked').each(function(){
allvals = $(this).val();
})
return allvals;
}
jQuery(document).ready(function($){
var deleteArray = [] ;
$('.categorySelect').click(function(){
deleteArray = categoryDelete();
$('#deleteArray').attr('value',deleteArray);
$('#deleteValue').attr('value',0);
})
$('.subcategorySelect').click(function(){
deleteArray = subcategoryDelete();
$('#deleteArray').attr('value',deleteArray);
$('#deleteValue').attr('value',1);
})
})
</script>
html表格:
{{ Form::open(array('url' => 'manage-category/delete')) }}
<input type="hidden" id='deleteArray' name='deleteArray[]'>
<input type="hidden" id='deleteValue' name='deleteValue[]'>
<button id='deleteBtn' class="btn btn-sm red pull-right">
Delete <i class="fa fa-times"></i>
</button>
{{ Form::close() }}
路线:
Route::post('/manage-category/delete','CategoryController@deleteCategory');
控制器:
public function deleteCategory()
{
$deleteArray = Input::get('deleteArray');
$deleteValue = Input::get('deleteValue');
var_dump($deleteArray);
die();
}
调试结果:
array(1) { [0]=> string(1) "2" }
答案 0 :(得分:2)
你说的allvals = $(this).val();
每次都会覆盖所有的值。所以它只会存储最后一个复选框的值。
解决方案是添加新值。
allvals.push($(this).val());