【发布时间】:2014-10-01 23:29:34
【问题描述】:
我有将下拉菜单中的项目添加到列表框中的代码。当用户提交表单时,它会通过列表框并选择所有项目,然后更新表格。
如果用户从列表框中删除了所有项目,我在代码中添加了一个空白项目到列表框,这样列表框仍然可以更新。我必须这样做,因为如果列表框中没有项目,那么它不会被更新并且旧项目会保留。
$.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>'));
}
现在,我想检查列表框中是否有超过 1 项,如果存在则删除此空白项。
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>
【问题讨论】: