tags:

views:

64

answers:

3

Hi All,

I have a select box that gets generated dynamically. I want to allow users to create more copies of this select box if they need to but I want to avoid extra database calls so I want to use clone() instead of an AJAX load(). The problem is that I need an input field after each select box, so the user can enter a value. The clone() method acts as expected, creating a new select box and input box, A side effect of this is that the clone() also clones the input field element value, too, which needs to be value="". Any suggestions would be appreciated.




// set_add_delete_links makes sure that we dont show a [-] button 
// if there is only 1 element
// and that we only show a [+] button on the last element
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;
}
function addselect(s){
 $('#product_categories > .category_block:last').after(


     $('#product_categories > .category_block:last').clone()



   ); 



 set_add_delete_links(); 
 return false;
}

$(document).ready(

                  function(){
                        set_add_delete_links();
                  }
            );

<div id="product_categories">
    <div class="category_block">
        <select name="category_ids[]" id="cat_list">
            <option value="">Select a Property</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>
</div>
+1  A: 

Try:

var myClone = $('#product_categories > .category_block:last').clone();
$('input.specsinput', myClone).val(''); // clear the value of the input
Ken Browning
+1  A: 
function addselect(s){
 $('#product_categories > .category_block:last').after(
     $('#product_categories > .category_block:last').clone()
   ); 
 $('#product_categories > .category_block:last input').val(""); // this resets the value to ""
 set_add_delete_links(); 
 return false;
}
Jakub Hampl
A: 

Do some processing on the cloned segment of the DOM.

Like:

xxx.after($('#product_categories > .category_block:last').clone().find('input').val(''));
scaryzet