How to refresh a div without losing the style and plugin (select2) using jquery

Viewed 271

In the HTML I am trying to reload this div below;

           <select name="test[]" id="test" multiple required
                   class="select2">
               @foreach($tests as $s)
                     <option value="{{ $s->id }}" {{ ( in_array($s->id, $tests) ) ? 'selected="selected"' : '' }}>
                             {{ $s->value }}
                      </option>
                @endforeach
           </select>

I am using a script to reload the content but losing the select2 functionality for the div here is the snippet I am using to refresh the tag

 $( "#test12" ).load(window.location.href + " #test" );
2 Answers

you need to re-initiate the select2 plugin after every refresh of your div element.

because select2 gets bind via script once you called .select2() on your select tag, and whenever you refresh the div element in which your select tag is there, the binding will be removed, and it will became normal default select dropdown. So for binding it again you have to rebind it.

You can try these ways to do it. $("#test").select2(); or $("#test").select2("refresh");

I am new here though; all these didnt work for me.

I had to get the value of the $( "#test12" ) and push the new created object from the endpoint into the $( "#test12" ) value. you will now have all the updated data.

Related