Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting multiple choices using jquery chosen plugin

I'm using chosen's plugin to select multiple items from data loaded from a database. This is saved, and then I might want to load those choices again (the entire form, really) to edit it, and save changes.

I can successfully read the various choices from the select component like so:

$("#meet_participants").chosen().val();

However If I want to set the multiple choices I'm trying this test case:

HTML code:

<div class="row">
  <div class="form-group">
    <label class="control-label">Participantes</label><br>
    <b>
    <select data-placeholder="Ingrese los nombres" class="chosen-select form-control" style="width:60%" multiple id="meet_participants">
    <!--Filled with all db users.-->
    <option>hola</option>
    <option>mundo</option>
    <option>cruel</option>
    <option>como</option>
    <option>estas</option>
    </select>
    </b>
    <button class="btn btn-primary"><b>Tareas pendientes</b></button>
  </div> <!--formgroup-->
</div> <!--row-->

The after that I do (as per the example)

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/plugins/jquery-1.11.1.min.js"></script>
<script src="js/plugins/bootstrap.min.js"></script>  
<script src="js/plugins/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
  var config = {
'.chosen-select'           : {},
'.chosen-select-deselect'  : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
  }
  for (var selector in config) {
$(selector).chosen(config[selector]);
  }
</script>


<script>
  fillMemoForm();
  $("#meet_participants").chosen().val(["hola", "mundo", "cruel"]);
</script>

Only the last line is important, however I pasted everything just in case. As I understand this should have set the selected values to these three items, but it didn't. What am I doing wrong?

like image 693
aarelovich Avatar asked Dec 26 '22 02:12

aarelovich


1 Answers

A better solution for this instead of destroying and re-creating dom element would be

$('#meet_participants').val(["hola","mundo","cruel"]).trigger('chosen:updated');
like image 169
Sercan Ozdemir Avatar answered Jan 04 '23 23:01

Sercan Ozdemir