Home > Mobile >  How to deselect select input with jquery?
How to deselect select input with jquery?

Time:09-23

I use enter image description here

My cod exist in JSFiddle too. I want deselect all with JQuery. I use so many code but not working for this option.

var elements = document.getElementById("field2").selectedOptions;

    for(var i = 0; i < elements.length; i  ){
      elements[i].selected = false;
    }

or

document.getElementById("field2").value = "";

or

$('#field2').find($('option')).attr('selected',false)

CodePudding user response:

With the specific plugin you're using, you can clear the selection with

$("#id").val("");

and you can reset the wrapper using

$("#id")[0].loadOptions()

([0] as it's a js function added by the wrapper)

Updated snippet:

$("#clearBtn").click(() => {
  $("#field2").val("");
  $("#field2")[0].loadOptions();
});
select {
  width: 20em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://www.cssscript.com/demo/filterable-checkable-multi-select/multiselect-dropdown.js"></script>

<div >
  <div >
    <div >
      <label>Select 2</label>
      <select name="field2" id="field2" multiple multiselect-search="true" multiselect-select-all="true" multiselect-max-items="3" onchange="console.log(this.selectedOptions)">
        <option>Abarth</option>
        <option>Alfa Romeo</option>
        <option>Aston Martin</option>
        <option>Audi</option>
        <option>Bentley</option>
        <option>BMW</option>
        <option>Bugatti</option>
        <option>Cadillac</option>
        <option>Chevrolet</option>
        <option>Chrysler</option>
        <option>Citroën</option>
        <option>Dacia</option>
        <option>Daewoo</option>
        <option>Daihatsu</option>
        <option>Dodge</option>
        <option>Donkervoort</option>
        <option>DS</option>
        <option>Mazda</option>
        <option>McLaren</option>
        <option>Mercedes-Benz</option>
        <option>Skoda</option>
        <option>Smart</option>
        <option>SsangYong</option>
        <option>Subaru</option>
        <option>Suzuki</option>
        <option>Tesla</option>
        <option>Toyota</option>
        <option>Volkswagen</option>
        <option>Volvo</option>
      </select>
    </div>
  </div>
</div>


<hr />
<button id='clearBtn'>clear</button>

  • Related