William Xavier
William Xavier

Reputation: 478

Mark dropdown value as selected with jquery

i have a little problem with my dropdowns, i want to validate them when the value is not 0, so i've used this code:

$('select[name=seguimento]').change(function(){
    $('option:selected',this).attr('selected', true);
});

The problem is that when i change the option, it turns selected, but when i change it again, it keep marking all as selected instead of removing the already selected options.

I have searched everywhere but didn't found a solution for this.

How can i do this? Thanks!

Upvotes: 1

Views: 808

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You will have to remove the selected attribute from the unselected option elements so

$('select[name=seguimento]').change(function () {
    $('option[selected]:not(:selected)', this).removeAttr('selected');
    $('option:selected', this).attr('selected', true);
});

If all the option elemnets are siblings(ie, optgroup is not used then)

$('select[name=seguimento]').change(function () {
    $('option:selected', this).attr('selected', true).siblings('[selected]').removeAttr('selected');
});

Upvotes: 2

Related Questions