Home > Software engineering >  How can clean a select2 option selected after main option changed with json values?
How can clean a select2 option selected after main option changed with json values?

Time:06-14

I'm trying to cleanup all options when the fisrt select2 changed.

The code actually is working fine but when the first select option changed the third select2 is still active showing the old value.

<html lang="en">
<head> 
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
</head>
<body>

 <select name="customerId" id="customerId">
   <option value="">Seleccione</option>
 </select>

 <select name="customerDetail" id="customerDetail"></select>

<select name="customerDetail2" id="customerDetail2"></select>

<script>
let getCustomers = async (id, path) => {
    let data = []
    await fetch(path)
        .then(response => response.json())
        .then(response => {
            data = response.map((value, index) => {
                return {
                    id: value.id,
                    text: value.name
                }
            })
            $(id).select2({
                placeholder: "Seleccione",
                width: '250px',
                data: data
            })
        });
    return data
}
let getCustomerDetails = async (id, path, $el, field) => {
    let data = []
    await fetch(path)
        .then(response => response.json())
        .then(response => {
            let filter = response.filter((value, index) => {
                return ($el.value == value[field])
            })
            data.push({
                id: 0,
                text: 'Seleccione',
            }) 
            filter.forEach((value, index) => {
                data.push({
                    id: value.id,
                    text: value.name
                })
            })
            $(id).empty()
            $(id).select2({
                placeholder: "Seleccione",
                width: '250px',
                data: data
            })
        });
    return data
}
$(window).on('load', () => {
    $('select').select2({
        placeholder: "Seleccione",
        width: '250px',
    })
    getCustomers('#customerId', 'customers.json')
    
    $('#customerId').on('change', (e) => {
        let $element = e.target
        getCustomerDetails('#customerDetail', 'customersDetails.json', $element, 'customer_id')
    })
    $('#customerDetail').on('change', (e) => {
        let $element = e.target
        getCustomerDetails('#customerDetail2', 'customersDetails.json', $element, 'customer_owner')
    })
})

</script>

</body>
</html>

Here is the customers.json

[
 {
   "id": 1,
   "name": "company demo"
  }
]

Here is customerDetails.json

[
 {
   "id": 1,
   "customer_id": 1,
   "customer_owner": 1,
   "name": "Customer detail 1",
 }
]

I will appreciate all your comments.

Honestly i don't know how to display on jsfiddle but the information is here:

https://jsfiddle.net/cmorales/cw91ts3n/2/

CodePudding user response:

In order to clean selected value try using following code:

$('#idOfSelectElement').prop('selectedIndex',-1);

Where #idOfSelectElement - as it's name says is the name of select id.

This piece of code covers <select multiple> and it doesn't trigger change event.

In order to trigger change event you will have to add .trigger( "change" ); after :

$('#idOfSelectElement').prop('selectedIndex',-1).trigger( "change" );

CodePudding user response:

From the docs, the section titled Clearing selections:

You may clear all current selections in a Select2 control by setting the value of the control to null:

$('#mySelect2').val(null).trigger('change');

In your case you could use this inside the change handler, eg:

$('#customerId').on('change', (e) => {
    // First reset the other 2 select2s
    $('#customerDetail, #customerDetail2').val(null).trigger('change');

    // ... rest of your code ...
});
  • Related