mercredi 18 juillet 2018

How to submit a form based on an if/else statement

I have a form that contains clothing sizes. When a user selects a size, they are able to submit the form. My issue is that the user is able to submit the form whether or not they have selected a size. The code is much more complicated but below is a break down of the form, with the add to bag button below.

<form>
   <ul>
     <li>
      <ul>
       <li class="size-value"></li>
       <li class="size-value"></li>
       <li class="size-value"></li>
       <li class="size-value"></li>
     </ul>
    </li>
  </ul>
</form>
<div class="mt10">
   <input type="submit" class="modalAddToBagButton">
</div>

When a user selects a size, the class "selected" is added, so it would read class="size-value selected". This function is working fine. In my js file I would like to add an if/else statement, where if an has been given the class "selected" (the user has clicked this size), then the form will be submitted, however if NO li has the class "selected", the form will throw an error message. Below is the section of my function that I believe I should add the if/else statement:

}).on('click', '.modalAddToBagButton', function(e) {
            e.preventDefault();
            // Add if/else statement here. if list items have a class selected, form can be submitted. if no list items have class selected, then display this error message.
            $(this).closest("#dialog-addToBag").find('form').submit();
        });

My question is: How do I write this if/else statement? I am not sure how to access the form and list items from my input button, since they are outside the div and are quite nested, and to listen for if any of the list items have been given the class "selected" so that the form can be submitted, and if not to throw an error message. Can anyone help with this?

Aucun commentaire:

Enregistrer un commentaire