How to get selected value after clone with jQuery?

omg picture omg · Aug 31, 2009 · Viewed 8.6k times · Source

Here is my complete testing code,which failed to get the value:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="en-us" />
    <title>Job Search</title>
    <script language="javascript" type="text/javascript" src="script/jquery-1.3.2.js"></script>
    <script language="javascript">
        $(document).ready(function(){
            $('#test').click(function(){
                $('#container').clone().attr('id', 'container2').find('select').each(function() {
                    var $elem = $(this);
                    var value = $elem.val();
                    alert(value);
                });
            });
        });
    </script>
</head>

<body>
<div id="container">
    <select>
        <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" />
</body>

</html>

Answer

rahul picture rahul · Aug 31, 2009
$('#container').clone().attr('id', 'container2').find('select > option').each(function() {
                var $elem = $(this);
                var value = $elem.val();
                alert(value);
            });

Changed the selector in find method to select > option from select.

Also why are you cloning the element if you are not going to append it to the DOM.

To get the selected value of the cloned element you can use

$('#container').clone().attr('id', 'container2').find('select > option:selected').val()

If you need to insert the cloned element to the DOM you can use

$('#container').clone().attr('id', 'container2').appendTo("body")

and full code for getting the selected option value after inserting the cloned element to the DOM

$('#container').clone().attr('id', 'container2').appendTo("body").find('select > option:selected').val()

Complete code for the button click

 $(document).ready(function(){
            $('#test').click(function(){
                $('#container').clone().attr('id', 'container2').appendTo("body").find('select > option:selected').each(function() {
                    alert ( $(this).val());
                });
            });
        });