Francisco Lemos
Francisco Lemos

Reputation: 63

How to continue in jQuery loop?

I am new to jQuery and I want to loop through the elements of a form, however there are textareas that have class with 'hide' and I want to continue to the next element. I have the following code:

jQuery(document).ready(function(){jQuery('#helpdesk_ticket_submit').on('click', function(e){
      submitText = ""
      jQuery('#new_helpdesk_ticket input, #new_helpdesk_ticket select, #new_helpdesk_ticket textarea').each(
        function(index){  
            var input = jQuery(this);
            if (input.prev().is('textarea'))
              if (input.attr('class').indexOf('hide') >= 0) 
                continue;

            submitText += "<p><b>" + input.attr('id') + "</b>" + "<code>: </code>" + input.val() + "</p>"
        }
      );
      window.open().document.write(submitText);
  });
});

I am getting the following error: Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement

How is it possible to continue the loop when it finds a textarea with a class with the word hide?

Thanks

Upvotes: 1

Views: 399

Answers (1)

Sascha A.
Sascha A.

Reputation: 4626

Use return; to continue the each-loop from jQuery.
If you want to break use return false;.

jQuery(document).ready(function(){jQuery('#helpdesk_ticket_submit').on('click', function(e){
      submitText = ""
      jQuery('#new_helpdesk_ticket input, #new_helpdesk_ticket select, #new_helpdesk_ticket textarea').each(
        function(index){  
            var input = jQuery(this);
            if (input.prev().is('textarea'))
              if (input.attr('class').indexOf('hide') >= 0) 
                return;

            submitText += "<p><b>" + input.attr('id') + "</b>" + "<code>: </code>" + input.val() + "</p>"
        }
      );
      window.open().document.write(submitText);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 3

Related Questions