How do I reset chosen-jquery?

132 Views Asked by At

I'm using jquery 3.3.1 slim min and chosen 1.8.7

inside a form I have a select multiple and a reset button:

<form>
  <select id="users" name="users" tabindex="2" class="form-control chosen-select" multiple>
    <option value=""></option>
    <option value="1">1</option>
  </select>

  <button type="button">
    Clear
  </button>

</form>

I do the initialization of the chosen:

$("#users")
  .chosen({
    no_results_text: "Oops, nothing found!",
  })
  .change(function(event) {

    if (event.target == this) {

      $users = $(this).val()
    }
  })

and when i try to reset the chosen, it doesn't update the html interface:

$('button').on('click', function() {
  $("#users").val([]).trigger('chosen:updated')
})

What am I forgetting?

with that, I expected that it would update the interface, however it resets the value but does not update the interface html

$("#users").val([]).trigger('chosen:updated')

I also tried without success

$("#users").val('').trigger('chosen:updated')

Edit

before: before

Add options Add options

Console Console

options were not removed, however the value was reset after

1

There are 1 best solutions below

9
Jordy On

Looks like your code works. Maybe you are missing importing the CSS library so that's makes confusion:

https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css

$("#users")
  .chosen({
    no_results_text: "Oops, nothing found!",
  })
  .change(function(event) {

    if (event.target == this) {

      $users = $(this).val()
    }
  });

$('button').on('click', function() {
  $("#users").val('').trigger('chosen:updated')
});

$('a').click(()=>{
  console.log($('#users').val());
});
select {
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css" rel="stylesheet"/>
<form>
  <select id="users" name="users" tabindex="2" class="form-control chosen-select" multiple>
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>

  <button type="button">
    Clear
  </button>
  <a href="#">Check Value</a>

</form>