How to use multiple conditions within an if

Asked

Viewed 2,810 times

3

I’ve tried several ways, grouping with () in all the ways I imagined, creating a variable and calling it in condition etc, but I can find where I’m missing.

$(function() {
    $('#id1').change(function(){
       if (($(this).val() == '3' || '4') && ('id2' == '5')) {
       $('#div1').fadeIn('slow');
       $('#div2').hide();
        }
       else if ($(this).val() == '6' || '7') {
           $('#div1').hide()
       }
        else {
           $('#div2').hide();
           $('#div1').hide();
        }
    });
});

I’ve tried that too:

var tip = document.getElementById("#id2").val;
       if (($(this).val() == '3' || '4') && (tip == '5'))

And grouping it differently:

if ($(this).val() == '3' || '4' && 'id2' == '5')

Or

if (($(this).val() == '3' || '4') && 'id2' == '5')

Follows a https://jsfiddle.net/gustavox/6e7yo7y2/2/ with the example.

1 answer

7


Logical operators evaluate the Booleans returned in predicates, they must be used between two expressions (which result in a Boolean), or Booleans themselves (true or false)

You’re wrong in this condition:

($(this).val() == '3' || '4')

it should be as follows:

($(this).val() == '3' || $(this).val() == '4')

Follow the correction of your fiddle : https://jsfiddle.net/7t9u4yeq/

Comments on your fiddle:

first mistake

The line var tip = document.getElementById("#id2").val; is wrong, because to recover the value of a select list using javascript you must return the value of the selected option, then in the case would be:

var tip = document.getElementById("id2").options[e.selectedIndex].value

or using jquery

var tip = $("#id2").val();

second mistake

The conditions as already mentioned in this answer

third mistake

The event must be captured when either of the two dropdowns is modified, then one more selector must be added to the event

$('#id1, #id2').change(function(){}

As now the event can be called in any of the dropdowns we must change in the condition where we use $(this).val(), for $('id1').val()

  • 1

    Very good, thanks really, clarified a lot... Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.