Aman Gupta
Aman Gupta

Reputation: 1874

How to specify multiple && and || conditions in if statement in javascript?

I have a form which has three blocks face-book, twitter and pinterest. I added a condition to allow submitting the form only when one of the block is selected. For that I did:

if ($("#fb").prop("checked") || $("#tw").prop("checked")||
  $("#pin").prop("checked")) {
    ...
    ...
}
if ($("#fb").prop("checked") || $("#tw").prop("checked")||
  $("#pin").prop("checked")) {
    ...
    ...
}

Now I want to add another condition where it will check inside the twitter block to check if the text field has less than 140 characters. For that I added an and condition

if ($("#fb").prop("checked") || $("#tw").prop("checked") && $(#"tw_text").val().length <= 140||
  $("#pin").prop("checked")) {
    ...
    ...
}

But this has some faults like if the facebook is selected and tw_text has more than 140 characters then also the form gets submitted.

Please guide me to the correct way to add conditions to prevent submitting the form.

Upvotes: 1

Views: 1778

Answers (3)

Aman Gupta
Aman Gupta

Reputation: 1874

Solution: I used this way to resolve the issue.

if($("#fb").prop("checked") || $("#tw").prop("checked") || $("#pin").prop("checked")) { 
    if ($("#tw").prop("checked")) { 
        if($('#tw_text').val().length <= 140) { 
           ...submit form... 
        } 
        else { 
            .... show error for twitter text length.... 
        } 
    } 
    else { 
        ...submit form... 
    } 
} 
else { 
    ... show error message to select minimum one of the options between fb,tw and pinterest ... 
}

Upvotes: 0

user3327405
user3327405

Reputation: 1

From what I understand from your description is that only for twitter you need a compulsory condition to be satisfied. Simply using brackets should help you here. Hope the following helps: if ($("#fb").prop("checked") || ($("#tw").prop("checked") && $(#"tw_text").val().length <= 140) || $("#pin").prop("checked")) { ... ... }

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You need parentheses to group them (the precedence of logical OR || is smaller than logical AND &&):

if ($("#fb").prop("checked") || 
    ($("#tw").prop("checked") && $(#"tw_text").val().length <= 140) ||
    $("#pin").prop("checked")) {
...

Upvotes: 4

Related Questions