javascript - 使用jquery从选择框中删除选定的值,但需要在选择框中显示当前选定的值?

标签 javascript jquery

我有一个select框并添加更多 button 。当我点击添加更多 button它正在创建另一个 select使用克隆。在第一个选择框中 I selectoption值来自 select框表示应从下一个创建的 select 中删除该值同时在当前value选择框中选择的值当前显示 select盒子。选择框值正在动态加载。

例如:

<select name="section" id="section_1" class="sectionType">
    <option value=" ">------</option>
    <option value="05">test1</option>
    <option value="06">test2</option>
    <option value="07">test3</option>
    <option value="08">test4</option>
    <option value="10">test5</option>
    <option value="11">test6</option>
    <option value="12">test7</option>
    <option value="13">test8</option>
    <option value="14">test9</option>
</select>

最佳答案

这是您要找的吗?

我建议您使用 index() 进行操作和操作,这不会影响您的动态值。

//Take a clone of last 
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last 
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
  //Finally append it
  $('body').append("<br/><br/>").append(cloneElement);
}

$('button').click(function(){
 
  //Take a clone of last 
  var cloneElement = $('.sectionType:last').clone();
  //Get index of option selected from last 
  var indexToRemove = $('.sectionType:last').find('option:selected').index();
  //Remove previously selected index
  cloneElement.find('option').eq(indexToRemove).remove();
  //Change the id of an element
  cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
  //If element has options
  if(cloneElement.find('option').length)
  {
    //Finally append it
    $('body').append("<br/><br/>").append(cloneElement);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
    <option value="">------</option>
    <option value="05">test1</option>
    <option value="06">test2</option>
    <option value="07">test3</option>
    <option value="08">test4</option>
    <option value="10">test5</option>
    <option value="11">test6</option>
    <option value="12">test7</option>
    <option value="13">test8</option>
    <option value="14">test9</option>
</select>
<button>Clone</button>

关于javascript - 使用jquery从选择框中删除选定的值,但需要在选择框中显示当前选定的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39739941/

相关文章:

javascript - 从数组中收集数据并使用复选框进行过滤

javascript - 在Jquery中获取所选图像的值

javascript - Angularjs ng-repeat 与过滤范围对象

javascript - 将 Json 数组合并为多维单数组

javascript - DIV并排,位置不正确

javascript - 编辑记录需要刷新页面

javascript - 在 HTML5、javascript/jquery 中固定/标记 map 上的多个位置

javascript - 如果在继承类中重新定义该字段,则无法从 super 的构造函数设置公共(public)类字段的值

JAvascript 180 到 -180 旋转

javascript - 使用回调动态更改 jQuery 插件的选项