我有一个代码,将下拉菜单中的项目添加到列表框中。当用户提交表单时,它通过列表框并选择所有项目,然后更新表格。JQuery检查空的列表框项目
如果用户从列表框中删除所有项目,我在代码中添加了一个空白项目添加到列表框,所以列表框仍然可以更新。我不得不这样做,因为如果在列表框中没有项目,那么它将不会被更新,并且旧项目将保留。
$.each(aListBoxes, function (idx, listBox) {
//If nothing in listbox add blank item so it can get updated
if ($("#" + listBox + " option").length < 1) {
($("#" + listBox).append('<option value=""></option>'));
}
现在,我想检查列表框中是否有多个项目,如果有的话删除这个空白项目,如果存在。
if ($("#" + listBox + " option").length > 1) {
$("#" + listBox + " option").each(function() {
//if item value is empty then remove
整个至今脚本:
<script type="text/javascript">
//for pre-selection of all elements in every list box
$(document).ready(function() {
var aListBoxes = [];
// get a list of all the listboxes on the form
$("[id*=" + "lbx" + "]:visible").each(function() {
aListBoxes.push(this.id);
});
//on btnSubmit click because the form gets posted each time an autopostback field is hit.
$("input[name=btnSubmit]").click(function() {
//just before submission, go through each of the listboxes and if they contain anything, select everything.
$.each(aListBoxes, function (idx, listBox) {
//If nothing in listbox add blank item so it can get updated
if ($("#" + listBox + " option").length < 1) {
($("#" + listBox).append('<option value=""></option>'));
}
//If more than 1 item check for blank and remove
if ($("#" + listBox + " option").length > 1) {
$("#" + listBox + " option").each(function() {
//if empty
//remove
});
}
//select all before submitting
if ($("#" + listBox + " option").length > 0) {
$("#" + listBox + " option").each(function() {
$(this).prop('selected', 'selected')
});
}
});
});
});
</script>
完美谢谢! – BringQBasicBack 2014-10-01 14:50:30
您的欢迎。请接受,以便其他人也知道如果他们在寻找相同的答案。快乐编码! – 2014-10-01 14:51:25