mpgn
mpgn

Reputation: 7251

basic conditions && or || in javascript

I can't understand why my code doesn't work. First i have this form :

form

The first area is compulsory && the last three only one is mandatory

So i try this code :

<div class="modal-body">
    <div class="filtre"></div>
    <h5>Ajouter votre filtre</h5>
    <p>Nom du filtre
        <input type="text" class="span12" name="nomFiltre" id="nomFiltre">
    </p>
    <p>De :</p>
    <input type="text" class="span12" name="provenanceFiltre" id="provenanceFiltre">
    <p>A :</p>
    <input type="text" class="span12" name="destinataireFiltre" id ="destinataireFiltre">
    <p>Objet : </p>
    <input type="text" class="span12" name="objetFiltre" id="objetFiltre">

</div>

And this JavaScript :

<script type="text/javascript">

    $(function(){
        $("#filtreVerif").click( function(){
            if($("#nomFiltre").val().length < 1 && $("#provenanceFiltre").val().length < 1 || $("#destinataireFiltre").val().length < 1 || $("#objetFiltre").val().length < 1){
                $('<div class="alert alert-error hide"><h4 class="alert-heading">Erreur !</h4>Vous devez entrer un titre est remplire au moins un des critéres !</div>').appendTo('.filtre').show("slow").delay(4000).hide("slow");
                return false;
            }
        });
    });

</script>

My problem is when i click next :

I want if one of the three fields is not empty mandatory then i return false.

Upvotes: 1

Views: 98

Answers (1)

Marcus
Marcus

Reputation: 5457

You need to put your ||'s in a separate set of parentheses

The way you have it now returns true if 1 and 2 are true, if 3 is true, or if 4 is true.

Edit Sorry, I was going the other way. You have to switch the ||'s and &&'s. It should be:

if($("#nomFiltre").val().length < 1 || ($("#provenanceFiltre").val().length < 1 && $("#destinataireFiltre").val().length < 1 && $("#objetFiltre").val().length < 1))

Upvotes: 2

Related Questions