gpt4 book ai didi

javascript - 确保多重选择元素选择了非空选项

转载 作者:行者123 更新时间:2023-12-03 03:50:17 26 4
gpt4 key购买 nike

我有一个下拉列表,其中默认选定选项的值为。单击提交按钮后,将调用 save() 函数,如果任何选择有“空”选择,则它会显示警报并中断。它显示警报,但如果我为每个选择选择一个选项,它永远不会提交该帖子。我做错了什么?

function save() {

let order = [];

$('select[name="statusSelect[]"]').each(function(){
let id = this[this.selectedIndex].id;
let value = this.value;

// if any of the selects values === 'empty' break
if (value === 'empty') {
console.log("empty");
$(".alertEmptySelect").show();
return;

// else continue if all selects have a value
order.push({id: id, status: value});
let data = JSON.stringify(order);

$.ajax({
method: 'put',
url: '',
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response){
$(".alertSubmitted").show("slow");
},
error: function (data) {
console.log(data);
let errorString = '';
$.each(data.responseJSON, function (key, value) {
errorString += '<li>' + value + '</li>';
});
$('.alertError').show().html(errorString);
}
});
}
});
}

我有一个由循环创建的表。每行都有自己的选择,这就是为什么我将其声明为数组

<select name="statusSelect[]" id="statusSelect" onchange="changeColor(this, {{$product->id}})" class="form-control" required>
<option value="empty" disabled selected hidden>Please Choose...</option>
<option id={{$product->id}} value="a">A</option>
<option id={{$product->id}} value="r">R</option>
</select>

最佳答案

首先需要从PUT改为POST看看Here

其次,您不必使用每个有效的选择去服务器,但您应该做的是收集数据,然后如果所有有效的选择都执行ajax请求,那么您的函数应该如下所示:

    function save() {

let order = [];
//as you have many selects you need this flag to cancel ajax
request if any select is empyt
let isEmpty = false;
$('select[name="statusSelect[]"]').each(function() {
let id = this[this.selectedIndex].id;
let value = this.value;
debugger;
// if any of the selects values === 'empty' break the each
//and set the flag to beak the ajax request
if (value === 'empty') {
console.log("empty");
$(".alertEmptySelect").show();
isEmpty = true;
return;
}
// order array must be in the each loop to carry all the data
order.push({
id: id,
status: value
});

});
if (isEmpty) {
console.log("save canceled");
return;
}
let data = JSON.stringify(order);
console.log(data);
//should be outside the each to go only one time to the sever (make sure to put the Url)
$.ajax({
method: 'post',
url: 'your Url',
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
console.log('success.');
$(".alertSubmitted").show("slow");
},
error: function(data) {
console.log('error');
console.log(data);
let errorString = '';
$.each(data.responseJSON, function(key, value) {
errorString += '<li>' + value + '</li>';
});
$('.alertError').show().html(errorString);
}
});
}

关于javascript - 确保多重选择元素选择了非空选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45200759/

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