JQuery code optimization

Here I am trying to detect a choice option[name='admin'], and if so, I check the box mentioned if I do not uncheck it.

Is there any better optimization for this code?

$("select option[name='admin']:selected").select(function () {
    $(".gestionSupervision").prop('checked', true);
});

$("select option[name='sei']:selected").select(function () {
    $(".gestionSupervision").prop('checked', false);
});

HTML:

<select name="role" id="role" class="form-control" disabled>
    <option value="admin">Administrateur</option>
    <option value="sei">Superviseur</option>
</select>

Thank you so much!

+3
source share
3 answers

You can use the code below for a simpler understanding:

$('select#role').on('change', function (e) {
    var optionSelected = $("option:selected", this),
        selectedVal = this.value;

    if(selectedVal == "admin") {
        $(".gestionSupervision").prop('checked', true);
    } else {
        $(".gestionSupervision").prop('checked', false);
    }
}).change();

Demo Screenshot

Or you can shorten the code above:

$('select#role').on('change', function (e) {
    var selectedVal = $(this).find('option:selected').val();
    $(".gestionSupervision").prop('checked', selectedVal == "admin");
}).change();

Demo Screenshot

+1
source

I think you need to use a change event

$("#role").change(function () {
    $(".gestionSupervision").prop('checked', $(this).find('option[value="admin"]').is(':selected'));
}).change();

Demo: Fiddle

+1
source

Maybe something like this:

$("select option:selected").select(function () {
    status = (this.val() == 'sei')
    $(".gestionSupervision").prop('checked', status);
});

No need to repeat all this and change only names / booleans.

0
source

All Articles