Reputation: 207
I am working with Jquery and I have a use case to add some elements dynamically on a button click.
While adding the 'select' dynamically, the select2 is not displayed when the add button is clicked for the first time, instead, a simple 'select' is displayed, and when we click on add button again, all the previous 'select' get formatted to select2.
I needed that when we click the add button, the first generated selects should also get the select2.
Following is the script:
var container = $(document.createElement('div')).css({
padding: '5px', margin: '20px', width: '400px', border: '1px solid',
borderTopColor: '#999', float: 'left', borderBottomColor: '#999',
borderLeftColor: '#999', borderRightColor: '#999'
});
var iCnt = 0;
function add()
{
if (iCnt <= 19) {
iCnt = iCnt + 1;
$(container).append($("<select class ='selinput' id=tb" + iCnt + " " + "value='Text Element " + iCnt + "' style='float : left; margin-right:70px;'>"));
//Add Property Selector
$(container).append(" ");
$(container).append($("<select class ='selinput2" + iCnt + "'' id=tb2" + iCnt + " " + "value='Text Element " + iCnt + " ' ><option value='equalto'>A</option><option value='notequalto'>B</option></select>"));
$(container).append(" ");
// ADD TEXTBOX.
$('select').select2({width : '20%'});
$(container).append('<input type=text class="input" id=tbtext' + iCnt + ' ' +
'placeholder="Value ' + iCnt + '" style="float : center;" /><br><br>');
// SHOW SUBMIT BUTTON IF ATLEAST "1" ELEMENT HAS BEEN CREATED.
if (iCnt == 1) {
var divSubmit = $(document.createElement('div'));
$(divSubmit).append('<input type=button class="bt"' +
'onclick="GetTextValue()"' +
'id=btSubmit value=Submit />');
}
// ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
$('#main').after(container, divSubmit);
}
// AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
// (20 IS THE LIMIT WE HAVE SET)
else {
$(container).append('<label>Reached the limit</label>');
$('#btAdd').attr('class', 'bt-disable');
$('#btAdd').attr('disabled', 'disabled');
}
}
Following is the link to js fiddle:
https://jsfiddle.net/hns0qk2b/43/
Please advise.
Upvotes: 1
Views: 1741
Reputation: 9283
Your only problem is that you need your new elements added to the DOM before you can initialize select2. Add the elements to the DOM first, then your code will work.
// ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
$('#main').after(container, divSubmit);
// Initialize select2
$('select').select2({width : '20%'});
See these changes applied to the fiddle: https://jsfiddle.net/zjafvr3u/1/
Upvotes: 2