0

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.