JQuery parameter that doesn't work for selection has not yet been added to the DOM

I am trying to select a specific parameter in a select element that has not yet been added to the DOM, but it does not seem to work. Am I trying to make it impossible?

I would like to click the "Add Selection" button and see a new selection item added to the DOM, with the option "0" selected.

Here a

Jsfiddle

HTML

<div id="container">
    <select class="mySelect">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2" selected>2</option>
    </select>
</div>

<button id="addSelect">Add Select</button>

Js

$(document).ready(function() {
    var $template = $('.mySelect').first().clone(),
        $container = $('#container');

    $template.find('option').each(function(i, option) {
       $(option).prop('selected', false); 
    });

    $('#addSelect').click(function(e) {
        e.preventDefault();
        $container.append($template.clone());
    });
});

As you can see in the fiddle, a new selection is added, but it has the option "2".

I also tried resetting with help $template.val('0'), but that didn't work either. The selection is still displayed with "2" selected.

+4
source share
3 answers

selected, DOM , DOM:

$template.find(':selected').removeAttr('selected');

-DEMO -

+4
 $('#addSelect').click(function(e) {
        e.preventDefault();
        var $a = $template.clone();
        $a.find('option').prop('selected',false)
        $container.append($a);
    });

fiddle.

0
$template.find('option:selected').removeAttr('selected');

http://jsfiddle.net/Lm7d714q/8/

0
source

All Articles