tags:

views:

186

answers:

1

html:

<div id="container">
    <select id="selector">
     <option value="">--</option>
     <option value="Service">Service</option>
     <option value="Sales">Sales</option>
     <option value="Marketing">Marketing</option>
     <option value="Finance">Finance</option>
     <option value="Engineering">Engineering</option>
     <option value="Management">Management</option>
    </select>
</div>
<input type="button" id="test" />

script without clone(),works all right:

$('#test').click(function(){
    $('#container').find('select').each(function() {
        var $elem = $(this);
        var value = $elem.val();
        alert(value);
    });
});

script with clone(),not work:

$('#test').click(function(){
    $('#container').clone().attr('id', 'container2').find('select').each(function() {
        var $elem = $(this);
        var value = $elem.val();
        alert(value);
    });
});
+1  A: 

I don't know if this is the issue but you should note that when you clone a <select> element its selected item will be ignored if it was selected by the user. To get around this you can simply apply the selected DOM property to whichever option was originally selected. E.g.

$('#test').click(function(){

    var selectMenus = $('#container').find('select');

    $('#container').clone().attr('id', 'container2').find('select').each(function(i) {

        /* See this: */
        $('option', this)[selectMenus[i].selectedIndex].selected = true;

        var $elem = $(this);
        var value = $elem.val();
        alert(value);

    });

});

EDIT: I'm not sure if this is a cross-browser issue but it certainly affects FF3.5.

J-P
It works fine in IE 7.
rahul
This is no doubt a good solution,cheers!
Shore