Skip to content Skip to sidebar Skip to footer

Previous Fields Text Disappears When Adding New One With Select2 Ajax

I was using select2 plugin on my input box to search items from the database using AJAX based on what the user type on it. It was working fine, I can search Items on it and select

Solution 1:

The same id value is used for the input elements as rows get added.

It is best to have unique id within the page.


Solution 2:

I would guess that every time you call .select2(), that all the selects get reset to the original state. You could only call the constructor on the new box by limiting the scope.

To update only the new select2s you should change the following. See this example (untested, please adjust):

var newHtml = $("<h1>Code to be appended here</h1>");
newHtml.appendTo('#tblItemList tbody');
$('.itemSearch', newHtml).select2(/* ... */)

As an alternative you could try "freezing" the state by applying the "selected" attribute to all boxes before you call the constructor.

See this example (untested, please adjust)

$('.itemSearch').each(function(){
    var val = $(this).val();
    $(this).find('option[value='+val+']').attr('selected', 'selected');
})

Post a Comment for "Previous Fields Text Disappears When Adding New One With Select2 Ajax"