Run javascript function if condition is true

Asked

Viewed 152 times

0

Good night.

I have a button that when clicked, calls the function below:

$('#sa-success').click(function () {
   swal({
      title: 'Good job!',
      text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat, tincidunt vitae ipsum et, pellentesque maximus enim. Mauris eleifend ex semper, lobortis purus sed, pharetra felis',
      type: 'success',
      buttonsStyling: false,
      confirmButtonClass: 'btn btn-primary'
   });
});

But I wanted this function to be executed if a certain condition occurred in my IF. Example:

if(teste == true){
   $('#sa-success').click(function () {
      swal({
         title: 'Good job!',
         text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat, tincidunt vitae ipsum et, pellentesque maximus enim. Mauris eleifend ex semper, lobortis purus sed, pharetra felis',
         type: 'success',
         buttonsStyling: false,
         confirmButtonClass: 'btn btn-primary'
      });
   });
}

It is possible?

  • 6

    Why don’t you put the if within the event click?

  • You want to activate the click in #sa-success only if test is true is it? if yes, it works.

  • This function is not executed... it remains silent until the event occurs. The question has become a little pointless. Does as suggested, puts the if in.

  • 1

    This, the function is not executed, but this way if it does not pass in the if it is not tied to the element. But, it does with the if inside, it’s easier to understand.

1 answer

1


Following @Andersoncarloswoss' suggestion makes similar:

  $('#sa-success').click(function () {
      if (teste !== true) {
        return;
      }
      swal({
         title: 'Good job!',
         text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat, tincidunt vitae ipsum et, pellentesque maximus enim. Mauris eleifend ex semper, lobortis purus sed, pharetra felis',
         type: 'success',
         buttonsStyling: false,
         confirmButtonClass: 'btn btn-primary'
      });
   });

Browser other questions tagged

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