Home > Back-end >  Deselect all other class elements when this element is changed (jQuery)
Deselect all other class elements when this element is changed (jQuery)

Time:09-17

I have a few <select> elements that all have the same class alternate-linked-select-box. The intention here, is that when a change occurs to one select box, all the other ones should be deselected. Here is what I have so far:

$(document).ready(function() {
    $(".alternate-linked-select-box").on('change',(e) => {
        $(".alternate-linked-select-box").not($(e.target)).each((i,obj) => {
            $(obj).val([]);
        });
        // $(".alternate-linked-select-box").each((i,obj) => {
        //     if ($(obj) !== e.target) {
        //         console.log("We in here 2")
        //         $(obj).prop("selected", false);
        //     }
        // });
    });
});

Where the commented part demonstrates another approach I have tried to use. I have also tried to make use of $(this) but this also seems not to be working. Any ideas?

CodePudding user response:

You can select the option and set selected to false

// var sels = $(".alternate-linked-select-box").on("change", function() {
//   sels.not(this).find("option:selected").prop("selected", false);
// });

var sels = $(".alternate-linked-select-box").on("change", e => 
  sels.not(e.target).find("option:selected").prop("selected", false)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select >
  <option></option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select >
  <option></option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select >
  <option></option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

  • Related