Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery 'OR' statement (' | | ') is not working in if condition

Tags:

html

jquery

I have a dropdown with several options. I need to colorize those options as follows.

if Option value == "f1" OR Option value =="f2" then dropdown color = "blue"

else dropdown color = "red"

This is the code:

<select id="selector">
    <option value>Default</option>
    <option value="f1">Fruit 1</option>
    <option value="f2">Fruit 2</option>
    <option value="v1">Vege 1</option>
    <option value="v2">Vege 2</option>
</select>

<script>
    $('#selector').on('change', function()
    {
        var selected_v = this.value;

        $(this).find("option").css("color", "blue");
        $(this).css("color", "blue");

        if ((selected_v != "f1") || (selected_v != "f2")) {
            $(this).css("color", "red");
        }
    });
</script>

This is working for if ( (selected_v != "f1") ) but with second condition followed by || it doesn't work. With OR operator and second condition, all the options will be red. What is the wrong here?

Live code:

http://jsfiddle.net/s7ry1cvp/

like image 964
David Johns Avatar asked Dec 18 '25 08:12

David Johns


1 Answers

The problem is in the if statement. You are comparing the variable where it is NOT equal to a certain value, OR comparing again where it is NOT equal to a different value. Because of the OR it will always execute the code inside the if block. What is required is selected_v NOT equal to "f1" AND selected_v NOT equal to "f2".

Try using && operator:

if ( (selected_v != "f1") && (selected_v != "f2") ) {
    $(this).css("color", "red");
 }

Or you could code it as you stated:

if ( (selected_v == "f1") || (selected_v == "f2") ) {
   $(this).css("color", "blue");
}
else
{
    $(this).css("color", "red");
}
like image 175
haldo Avatar answered Dec 20 '25 01:12

haldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!