How to make a button prevent

Untill the if or if else statements is got to do

on click call the preventDefault something like:

(‘#test’).click(function(e)

e.preventDefault();

But how to allow to submit so not apply that preventDefault when the if or else if is do the job as arguments?

Thanks

I’d love to help you, but could you try rewording your question? And maybe posting more of your code so we can see what you are trying to do in context. And a link to the problem/assignment wouldn’t hurt.

Well I want to check on a type submit button all fields is filled or not and then display a message. But when all fields is filled then able to submit.

Can you post what you have so far?

 $('#the button').click(function(e)
 	{
 		e.preventDefault();
 		$(this).html('<b>send</b>');
 		if ($('#the input').val().trim().length === 0)
 		{
 			$('#message').show().text('the input is empty');
 		else
 		{
 			$('#message').show().text('you are abble to send');
 		}
 // cant submit because set preventDefault on function?
 	});

Why not use attr required on the HTML element instead?

$("input").attr("required", true);

I have set required on input. And well is a good one just try to display in a custom message what wrongs when submit the button. So not about browser notice. Also required not check is empty.

Well, instead of setting preventDefault on the event, maybe you should use return false when the conditions not met

if ($('#the input').val().trim().length === 0)
 		{
 			$('#message').text('the input is empty').show();
                        return false;
                }

this do same job not?

if ($(‘#the input’).val().trim().length === 0)
{
$(‘#message’).text(‘the input is empty’).show();
e.preventDefault();
}

return false; vs preventDefault();
?

There’re not, in JQuery, return false will do both these things: e.preventDefault and e.stopPropagation. FYI: https://www.mail-archive.com/jquery-en@googlegroups.com/msg71390.html

It is also worth noting that return false does not stop event propagation in non-jQuery event handlers.

1 Like

So in this case with if else what is better to use in your opinion? return false or preventDefault just?

Thanks.

I’d recommend you use the return false in this case, because what you really want is prevent the submit action if the conditions not met, is it not?

1 Like