ReynierPM ReynierPM - 23 days ago 16
HTML Question

Chained method calls doesn't work on original nor cloned element?

I have the following HTML:

<input type="text" id="condition_value_1" style="display: none" />
<button id="showme">Make Select2</button>
<button id="clickme">Make Input</button>


Then take a look to the following jQuery:

$(function() {
var cond1 = $('#condition_value_1');
var cloned_cond1 = cond1.clone();
var cond1_select = '<select name="condition_value_1" id="condition_value_1" multiple="multiple"><option></option><option value="1">Opt1</option><option value="2">Opt2</option></select>';

$('#showme').click(function() {
cond1.removeAttr('style').replaceWith(cond1_select).select2({
placeholder: 'Select choice'
});

});

$('#clickme').click(function() {
if ($('#condition_value_1').hasClass('select2-hidden-accessible')) {
$("#condition_value_1").select2('destroy');
}

$('#condition_value_1').replaceWith(cloned_cond1).removeAttr('style');
});
});


You can try the code above here.

Now as soon as you click on
#showme
you should remove the attr style, replace the original element with the given one and turn it into a Select2, the last part isn't working.

In the other side if you click on
#clickme
you should destroy the previous Select2 replace the
#condition_value_1
with the cloned element and remove the attr style because the cloned has that attribute but this is not working either.

The idea is to switch between elements and turn on/off properties on demand.

Maybe I am missing something here but I am not sure what. Could any help me here?


Note: I've deleted my previous post to avoid confusions, apologies about that!

Answer

The problem is because replaceWith() returns the original jQuery object which now contains no elements as you replaced them.

In your logic structure this means you can't chain from those elements and need to start calls on the appended elements, like this:

var $cond1 = $('#condition_value_1');
var $cloned_cond1 = cond1.clone();
var cond1_select = '<select name="condition_value_1" id="condition_value_1" multiple="multiple"><option></option><option value="1">Opt1</option><option value="2">Opt2</option></select>';

$('#showme').click(function() {
    $cond1.replaceWith(cond1_select);
    $('#condition_value_1').select2({
        placeholder: 'Select choice'
    });
});

$('#clickme').click(function() {
    if ($('#condition_value_1').hasClass('select2-hidden-accessible')) {
        $("#condition_value_1").select2('destroy');
    }

    $('#condition_value_1').replaceWith($cloned_cond1);
    $cloned_cond1.removeAttr('style');
});