【问题标题】:Multi-select add/remove select in jqueryjquery中的多选添加/删除选择
【发布时间】:2017-11-06 06:28:30
【问题描述】:

在一个表单中,我有两个多选。我可以使用以下 jquery 函数将 select1 中的项目添加到 select2 或从 select2 中删除项目:

<script  type="text/javascript">
   function addProject() {    
      return !$('#select1 option:selected').remove().appendTo('#select2');
   }

   function removeProject() {
      return !$('#select2 option:selected').remove().appendTo('#select1');
   }
</script>

<select multiple id="select1" class="form-control">
@for(p <- projects) {
    option value="@p.getName">@p.getName</option>
}
</select>

<button type="button" class="btn btn-primary"  onclick="addProject();" >
   <span class='glyphicon glyphicon-plus'></span>
</button>
<button type="button" class="btn btn-primary"  onclick="removeProject();" >
   <span class='glyphicon glyphicon-minus'></span>
</button>

<select name="projects" multiple id="select2" class="form-control">
</select>

问题是,如果我将项目添加到 select2 并提交表单,我会收到所有值。如果我添加和删除项目,反之亦然,我不会收到值。

我尝试在提交表单之前添加另一个 jquery 函数来选择 select2 中的所有项目,但没有成功。

function select_projects() {
    $('#select2').children('option').attr('selected', 'selected');
}

如何解决这个问题?

【问题讨论】:

  • 我检查过,但似乎与我的问题无关。
  • 就像在这个答案中所说的那样,当您想要更改您选择的项目时,您需要再次调用.select2() 函数。
  • 好的,但我的功能似乎运行良好。我可以毫无问题地添加/删除项目。我提交表单时出现的问题
  • 当我从 select2 中删除一个项目时,选择仍然在这个项目上,当我提交表单时 select2 没有选择任何项目

标签: javascript jquery


【解决方案1】:

我解决了更改 select_projects() 函数的问题,如下所示:

function select_projects() {
    $('#select1 option:selected').attr('selected', false);
    $('#select2').children().prop('selected', true);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2011-08-06
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多