Paolo Rossi
Paolo Rossi

Reputation: 2510

jquery add class on all input selected

I have a html form where I want highlight fields that have been selected via jquery. to do this I have done in this way

<select id="s1">
 <option value="">--</option>
 <option value="1">1</option>
 <option value="2" selected>2</option>
 <option value="3">3</option>
</select>

<select id="s2">
 <option value="">--</option>
 <option value="1">1</option>
 <option value="2">2</option>
 <option value="3">3</option>
</select>

<select id="s3">
 <option value="">--</option>
 <option value="1" selected>1</option>
 <option value="2">2</option>
 <option value="3">3</option>
</select>

etc..

js

if ($("select#s1 option:selected").prop("value") != '') {
 $("select#s1").addClass("blu-border");
}

if ($("select#s2 option:selected").prop("value") != '') {
 $("select#s2").addClass("blu-border");
}

if ($("select#s3 option:selected").prop("value") != '') {
 $("select#s3").addClass("blu-border");
}

etc..

I would like to know if it is possible to do this using only one command for all selected input fields. Like this that I use to reset all the form fields.

$(":input").prop('selectedIndex', 0);

Thanks

Upvotes: 0

Views: 1762

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to check whether the selected options value is not blank, so

$('select').removeClass('add').filter(function () {
    console.log(this, this.value)
    return this.value != ''
}).addClass('add')

Demo: Fiddle

Or

$('select').removeClass('add').has('option:selected[value!=""]').addClass('add')

Demo: Fiddle

Note: The removeClass() is used to remove the previously added class, in my test case.

Upvotes: 5

Related Questions