How to remove the selected element during a clone() operation

℡╲_俬逩灬. 提交于 2019-11-28 14:19:05

You need to clone the proper element, set the selected value for the clone, then append the clone.

function addselect(s){

        // Store the block in a variable
    var $block = $('#product_categories > .category_block:last');

        // Grab the selected value
    var theValue = $block.find(':selected').val();

        // Clone the block 
    var $clone = $block.clone();

        // Find the selected value in the clone, and remove
    $clone.find('option[value=' + theValue + ']').remove();

        // Append the clone
    $block.after($clone); 

    set_add_delete_links(); return false;
}

UPDATE: Modified to fit HTML added to question.

Please note, the ID of the select element is being cloned, which means you have 2 elements with the same ID. This is not allowed. You'll need to get rid of the ID, or change it in the clone to some other value.

You could do something like this before you append the clone:

    // Grab the select in the clone
var $select = $clone.find('select');

    // Update its ID by concatenating theValue to the current ID
$select.attr('id', $select.attr('id') + theValue);
baloo

You can save the cloned element to a variable that you manipulate before you insert it in the DOM. or re-select the new cloned element after it has been inserted and do the manipulations

See Best way to unselect a <select> in jQuery? on how to de-selecting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!