I have the following HTML code:
<input type="text" id="condition_value_1">
<span class="click_me">Click Me</span>
I am replacing the #condition_value_1
element with a SELECT type as follow and trying to turn the recently SELECT into a Select2:
$(function() {
$('.click_me').click(function(ev) {
var condition_value_1 = $('#condition_value_1');
var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
condition_value_1.replaceWith(select_html);
$('body').on('DOMNodeInserted', '#condition_value_1', function() {
$(this).select2({
placeholder: 'Start typing ...',
tags: true
});
});
});
});
But is not working since the element keep as a normal HTML Select type and doesn't turn into a Select2. Here is a Fiddle for you to play with. I am using jQuery 1.12.4 and Select 4.0.3.
How do I turn a dynamic element into a Select2 element? Any help?
Seems to work for me if not using DOMNodeInserted
event binding.
It's fair to assume the element has been added to the DOM when the replaceWith()
method is called.
$(function() {
$('.click_me').click(function(ev) {
var condition_value_1 = $('#condition_value_1');
var select_html = '<select name="condition_value_1" id="condition_value_1"></select>';
condition_value_1.replaceWith(select_html);
$('#condition_value_1').select2({
placeholder: 'Start typing ...',
tags: true
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.