Prevent next click with javascript

Howdy,
I need to perform some complex conditional logic with jquery/javascript on a form with multiple pages. I have logic working on click of the specific page’s next button. But I need to prevent the next click event from happening if my logic fails.

I have tried using e.preventDefault();, and searched for other options.

however, the event still submits / clicks next. here is a simplified version of my code:

var $next = $( '#gform_next_button_7_79' );
$next.on( 'click', function(e) {
	$('.gform_page:visible').hide();
	$('#gform_page_7_14').show();
	
	var elligible = true;
	if (elligible == true){
		$( '#gform_page_7_14' ).hide();
		$( '#gform_page_7_15' ).show();
	}else{
		$( '#gform_page_7_14' ).show();
		$('#gform_next_button_7_14 .gform_page_footer').prop('disabled', true)
	}
	e.preventDefault();
	return false;
});

Any help greatly appreciated.

Hi @user5d850a2a60b22044
It looks like you are trying to prevent the default next button behavior from happening by using e.preventDefault(); and return false;, but these lines of code are at the end of the click event handler function and will not be executed if the next page is shown.

To prevent the default next button behavior from happening, you can either:

  1. Return false at the beginning of the click event handler function:
var $next = $( '#gform_next_button_7_79' );
$next.on( 'click', function(e) {
	if (elligible == false){
		$( '#gform_page_7_14' ).show();
		$('#gform_next_button_7_14 .gform_page_footer').prop('disabled', true);
		return false;
	}

	$('.gform_page:visible').hide();
	$('#gform_page_7_14').show();
	
	if (elligible == true){
		$( '#gform_page_7_14' ).hide();
		$( '#gform_page_7_15' ).show();
	}
});
  1. Use the e.stopPropagation() method to stop the event from bubbling up to the parent elements and prevent the default behavior:
var $next = $( '#gform_next_button_7_79' );
$next.on( 'click', function(e) {
	if (elligible == false){
		$( '#gform_page_7_14' ).show();
		$('#gform_next_button_7_14 .gform_page_footer').prop('disabled', true);
		e.stopPropagation();
		return false;
	}

	$('.gform_page:visible').hide();
	$('#gform_page_7_14').show();
	
	if (elligible == true){
		$( '#gform_page_7_14' ).hide();
		$( '#gform_page_7_15' ).show();
	}
});

I hope this helps! Let me know if you have any questions.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.