0

I have a single select dropdown uses the choices library that includes a remove button and displays a variety of cities: example of drop down

It's declared in the code as:

<select class="cities-dd" placeholder="Select city:" style="font-size:16px;line-height:24px;font-weight:regular;color:#757575;width:350px;vertical-align:middle;">
     <option value="">Select city:</option>`
          for(let city of cities){
               if (city.length>2){
                   tab += `<option value="${city}">${city}</option>`;
                      }};  
</select>

I would like to clear the selected city using jQuery. I have tried a bunch of things including clicking the removeItemButton using:

jQuery(".choices__button, input[type='button']").click();

and changing the value to null via

jQuery(".cities-dd").val("").trigger("change");

but nothing seems to be working. Any suggestions would be much appreciated.

j08691
  • 204,283
  • 31
  • 260
  • 272
Jesse McMullen-Crummey
  • 3,175
  • 3
  • 8
  • 17

1 Answers1

1

From their documentation, I found that they have few methods to clear the selected values like clearChoices(), removeActiveItems(). Luckily, non of these works see this issue in github and I found a hack in your case. They have a method called setChoiceByValue(value) which is used to set the active element. In your case you have a placeholder option called Select city: with value "". So, what you can do is set it as a selected item by setChoiceByValue("");

See the following example:

console.warn = () => {};

const choices = new Choices($('.cities-dd')[0]);

$("#clear").off("click").on("click", function() {
  console.log(choices.getValue(true));
  choices.setChoiceByValue("");
  console.log(choices.getValue(true));
});
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css" rel="stylesheet" />
<select class="cities-dd" placeholder="Select city:" style="font-size:16px;line-height:24px;font-weight:regular;color:#757575;width:350px;vertical-align:middle;">
  <option value="">Select city:</option>
  <option value="London">London</option>
  <option value="Birmingham">Birmingham</option>
</select>
<button id="clear">
Clear
</button>
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71