简体   繁体   English

克隆一个 <select>没有一个<option>

[英]Cloning a <select> without one <option>

I have a select box with all european countries in there, the idea is that a person picks one or more countries that he/she does his/her business in. 我有一个选择框,其中包含所有欧洲国家/地区,其想法是一个人选择一个或多个在其开展业务的国家/地区。

This is how it looks right now: 现在是这样的:

在此处输入图片说明

And this is the javascript function: 这是javascript函数:

function AddCountry(element) {

    var oldSelect = jQuery("select[name='investor-country[]']").last();
    var newSelect = jQuery(oldSelect).clone();

    jQuery(element).before(newSelect);
}

So when the person clicks on the Add country link, the javascript gets executed and another <select> is inserted above the link (the links is also the parameter being sent). 因此,当该人单击“添加国家/地区”链接时,将执行javascript并将另一个<select>插入到链接上方(链接也是要发送的参数)。 This is an exact copy of the one before. 这是之前版本的精确副本。 The thing is I want it to remove the previous selected company from the list so the user can not (without having HTML knowlegde) enter two of the same countries. 问题是我希望它从列表中删除以前选择的公司,以便用户不能(没有HTML知识)输入两个相同的国家。

I tried alot but haven't succeeded. 我尝试了很多,但没有成功。 I tried all kind of weird jQuery combinations but mainly: 我尝试了所有奇怪的jQuery组合,但主要是:

newSelect.remove(0);

As far as I could find this should remove the first option from the list (0 can be replace with selectedIndex later) but it doesn't! 据我发现,这应该从列表中删除第一个选项(0以后可以替换为selectedIndex),但事实并非如此!

function AddCountry(element) {

    var oldSelect = jQuery("select[name='investor-country[]']").last();
    var newSelect = jQuery(oldSelect).clone();

    // Remove previously selected option
    var selected = oldSelect.val();
    newSelect.find("option[value="+selected+"]").remove();

    jQuery(element).before(newSelect);
}

删除所选选项的另一种方法:

newSelect.find('option').eq(oldSelect[0].selectedIndex).remove();

Try this: 尝试这个:

    //get the selected value
    var val = $("select[name='investor-country[]']").val();
    //get the selected option
    var option = $("option[value="+val+"]");
    //append the selected country somewhere
    $('#selected').append('<span>'+option.text()+'</span> ');
    //remove the selected option
    option.remove();

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM