How to delete selected item during clone () operation

I have a select box that is being cloned. I want to remove the previous user selection from each cloned selection field. Here is the method that clone() does:

 function addselect(s){ $('#product_categories > .category_block:last').after( $('#product_categories > .category_block:last').clone() ); set_add_delete_links(); return false; } function set_add_delete_links(){ $('.remove_cat').show(); $('.add_cat').hide(); $('.add_cat:last').show(); $("#product_categories > .category_block:only-child > .remove_cat").hide(); } function removeselect(s){ $(s).parent().remove(); set_add_delete_links(); return false; } 

This view works, but does not delete the last selected one:

  $('#product_categories > .category_block:last option:selected').remove(); 

Here is the HTML

 <div id="product_categories"> <div class="category_block"> <select name="category_ids[]" id="cat_list"> <option value="">Select Attribute</option> <option value="1770">Foo0</option> <option value="1773">Foo1</option> <option value="1775">Foo2</option> <option value="1765">Foo3</option> <option value="1802">Foo4</option> <option value="1766">Foo5</option> </select> <input class="specsinput" type="text" name="specs[]" value="" /> <a href="#" onClick="return removeselect(this);" class="remove_cat"> [-] </a> <a href="#" onClick="return addselect(this);" class="add_cat"> [+] </a> </div> 

+2
source share
2 answers

You need to clone the desired item, set the selected value for the clone, and then add 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 add HTML to the question.

Note that the identifier of the select element is cloned, which means that you have 2 elements with the same identifier. It is forbidden. You will need to get rid of the identifier or change it in the clone to some other value.

You can do something similar before adding a 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); 
+3
source

You can save the cloned element to a variable that you are manipulating before embedding it in the DOM. or re-select the new cloned item after inserting it and perform manipulations

See Best way to deselect <select> in jQuery? on how to deselect

+1
source

Source: https://habr.com/ru/post/1268205/


All Articles