Link to home
Start Free TrialLog in
Avatar of -Dman100-
-Dman100-Flag for United States of America

asked on

how to bypass preventDefault method

I am using jquery to validate some fields and display error messages when the required fields are not filled out. In my form, I have a section for an alternate address. If the user selects a checkbox for the alternate address, I make the street, city, state and zip required and use preventDefault to stop the form from submitting until those fields are filled out. The preventDefault method is stopping the form from getting submitted if the alternate address checkbox is selected.

Can a jquery expert take a look at my code and let me know how I can bypass the preventDefault when the alternate address checkbox is selected and all the required fields are correctly filled out?

Here is my jquery code:

 


I am using jquery to validate some fields and display error messages when the required fields are not filled out. In my form, I have a section for an alternate address. If the user selects a checkbox for the alternate address, I make the street, city, state and zip required and use preventDefault to stop the form from submitting until those fields are filled out. The preventDefault method is stopping the form from getting submitted if the alternate address checkbox is selected.

Can a jquery expert take a look at my code and let me know how I can bypass the preventDefault when the alternate address checkbox is selected and all the required fields are correctly filled out?

Here is my jquery code:
<script type="text/javascript">
    var j$ = jQuery.noConflict();

    j$(document).ready(function() {
        var submitButton = j$('[id$=btnSubmit]');
        var emailButton = j$('[id$=btnEmail]');
        var shippingMethod = j$('[id$=shippingMethod]');
        var alternateAddress = j$('[id$=chkbxAlternateAddress]');
        var alternateStreet = j$('[id$=alternateaddress]');
        var alternateCity = j$('[id$=alternatecity]');
        var alternateState = j$('[id$=alternatestate]');
        var alternateZip = j$('[id$=alternatezip]');
        submitButton.click(function(e){
            j$('[id$=documentQuantity]').each(function(index){
                if(j$(this).text() == '0') {
                    j$("#contentQtyError").css({"display":"inline"});
                    j$(this).parent().parent().css({"background-color":"#FFFFCC"});
                    e.preventDefault();
                }
            });             
            if(shippingMethod.val() == '') {
                if(j$('.shippingMethodErrorMsg').length == 0) {
                    shippingMethod.after("<span class='shippingMethodErrorMsg'>Error: A Shipping Method is Required</span>");
                }
                e.preventDefault();
            }
            else {
                j$(".shippingMethodErrorMsg").remove();
            }
            if(alternateAddress.attr("checked")) {
                if(j$('.alternateStreetErrorMsg').length == 0) {
                    alternateStreet.after("<span class='alternateStreetErrorMsg'>Error: A Street Address is Required</span>");
                }
                if(j$('.alternateCityErrorMsg').length == 0) {
                    alternateCity.after("<span class='alternateCityErrorMsg'>Error: A City is Required</span>");
                }
                if(j$('.alternateStateErrorMsg').length == 0) {
                    alternateState.after("<span class='alternateStateErrorMsg'>Error: A State is Required</span>");
                }
                if(j$('.alternateZipErrorMsg').length == 0) {
                    alternateZip.after("<span class='alternateZipErrorMsg'>Error: A Zip is Required</span>");
                }
                e.preventDefault();
            }
            else {
                j$(".alternateStreetErrorMsg").remove();
                j$(".alternateCityErrorMsg").remove();
                j$(".alternateStateErrorMsg").remove();
                j$(".alternateZipErrorMsg").remove();
            }
        });
        shippingMethod.change(function(){
            if(shippingMethod.val() == 'Email') {
                emailButton.css({"display":""});
                submitButton.css({"display":"none"});
                j$('#containerAltAddressToggle').css({"display":"none"});
                j$('[id$=chkbxAlternateAddress]').attr('checked',false);
                j$('[id$=alternateAddressPanel]').css({"display":"none"});
                j$('#containerCustomKitToggle').css({"display":"none"});
                j$('[id$=chkbxCustomKit]').attr('checked',false);
                j$('[id$=customKitPanel]').css({"display":"none"});             
                j$('#containerPersonalNoteToggle').css({"display":"none"});
                j$('[id$=chkbxPersonalNote]').attr('checked',false);
                j$('[id$=personalNotePanel]').css({"display":"none"});
                j$('#containerFollowUpTaskToggle').css({"display":"none"});
                j$('[id$=chkbxScheduleTask]').attr('checked',false);
                j$('#recurrence').css({"display":"none"});
                j$('[id$=commentsBlock]').css({"display":"none"});
            }
            else {
                emailButton.css({"display":"none"});
                submitButton.css({"display":""});
                j$('#containerAltAddressToggle').css({"display":""});
                j$('#containerCustomKitToggle').css({"display":""});                
                j$('#containerPersonalNoteToggle').css({"display":""});
                j$('#containerFollowUpTaskToggle').css({"display":""}); 
                j$('[id$=nextTask]').val("");   
                j$('[id$=commentsBlock]').css({"display":""});      
            }                           
        });
        alternateAddress.change(function() {
            if(alternateAddress.attr("checked") != "checked") {
                j$(".alternateStreetErrorMsg").remove();
                j$(".alternateCityErrorMsg").remove();
                j$(".alternateStateErrorMsg").remove();
                j$(".alternateZipErrorMsg").remove();
            }
        });
    });  
</script>
 
Any help is appreciated. Thanks!

Open in new window

Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Keep the prevent default, just don't submit the form unless the data you are expecting is there.   Make sure this is only your first line of defense.  Your real data authentication should be serverside.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of -Dman100-

ASKER

Hi and thanks for the response to my message.  I'm somewhat new to jquery so I'm floundering a little with my code.  I appreciate your help.

The reason I'm using ['id$=btnSubmit']  is how the id is generated on the Salesforce platform.  The button is attached to an action method in my controller which runs the code.

I revised my code to the following.  You were correct, I wasn't validating my alternate address input fields, which I changed to look at the input value length.  However, one issue I'm getting is that the error message I'm adding is getting added every time I click the submit button.  Is there a way to only add the error message once?  Also, I have some redundancy in my code, which I would like to improve and clean up.

    <script type="text/javascript">
        var j$ = jQuery.noConflict();
        		
		j$(document).ready(function() {
			var submitButton = j$('[id$=btnSubmit]');
			var emailButton = j$('[id$=btnEmail]');
			var shippingMethod = j$('[id$=shippingMethod]');
			var alternateAddress = j$('[id$=chkbxAlternateAddress]');
			var alternateStreet = j$('[id$=alternateaddress]');
			var alternateCity = j$('[id$=alternatecity]');
			var alternateState = j$('[id$=alternatestate]');
			var alternateZip = j$('[id$=alternatezip]');
			var isValid = true;
			submitButton.click(function(e){
				j$('[id$=documentQuantity]').each(function(index){
					if(j$(this).text() == '0') {
						j$("#contentQtyError").css({"display":"inline"});
						j$(this).parent().parent().css({"background-color":"#FFFFCC"});
						e.preventDefault();
					}
				});				
				if(shippingMethod.val() == '') {
					if(j$('.shippingMethodErrorMsg').length == 0) {
						shippingMethod.after("<span class='shippingMethodErrorMsg'>Error: A Shipping Method is Required</span>");
					}
					e.preventDefault();
				}
				else {
					j$(".shippingMethodErrorMsg").remove();
				}
				if(alternateAddress.attr("checked")) {
					if(alternateStreet.val().length == 0) {
						isValid = false;
						alternateStreet.after("<span class='alternateStreetErrorMsg'>Error: A Street Address is Required</span>");
					}
					else {
						j$(".alternateStreetErrorMsg").remove();
						isValid = true;
					}
					if(alternateCity.val().length == 0) {
						isValid = false;
						alternateCity.after("<span class='alternateCityErrorMsg'>Error: A City is Required</span>");
					}
					else {
						j$(".alternateCityErrorMsg").remove();
						isValid = true;
					}
					if(alternateState.val().length == 0) {
						isValid = false;
						alternateState.after("<span class='alternateStateErrorMsg'>Error: A State is Required</span>");
					}
					else {
						j$(".alternateStateErrorMsg").remove();
						isValid = true;
					}
					if(alternateZip.val().length == 0) {
						isValid = false;
						alternateZip.after("<span class='alternateZipErrorMsg'>Error: A Zip is Required</span>");
					}
					else {
						j$(".alternateZipErrorMsg").remove();
						isValid = true;
					}
				}
				if(!isValid) {
					e.preventDefault();
				}
			});
			shippingMethod.change(function(){
				if(shippingMethod.val() == 'Email') {
					emailButton.css({"display":""});
					submitButton.css({"display":"none"});
					j$('#containerAltAddressToggle').css({"display":"none"});
					j$('[id$=chkbxAlternateAddress]').attr('checked',false);
					j$('[id$=alternateAddressPanel]').css({"display":"none"});
					j$('#containerCustomKitToggle').css({"display":"none"});
					j$('[id$=chkbxCustomKit]').attr('checked',false);
					j$('[id$=customKitPanel]').css({"display":"none"});				
					j$('#containerPersonalNoteToggle').css({"display":"none"});
					j$('[id$=chkbxPersonalNote]').attr('checked',false);
					j$('[id$=personalNotePanel]').css({"display":"none"});
					j$('#containerFollowUpTaskToggle').css({"display":"none"});
					j$('[id$=chkbxScheduleTask]').attr('checked',false);
					j$('#recurrence').css({"display":"none"});
					j$('[id$=commentsBlock]').css({"display":"none"});
				}
				else {
					emailButton.css({"display":"none"});
					submitButton.css({"display":""});
					j$('#containerAltAddressToggle').css({"display":""});
					j$('#containerCustomKitToggle').css({"display":""});				
					j$('#containerPersonalNoteToggle').css({"display":""});
					j$('#containerFollowUpTaskToggle').css({"display":""});	
					j$('[id$=nextTask]').val("");	
					j$('[id$=commentsBlock]').css({"display":""});		
				}							
			});
			alternateAddress.change(function() {
				if(alternateAddress.attr("checked") != "checked") {
					j$(".alternateStreetErrorMsg").remove();
					j$(".alternateCityErrorMsg").remove();
					j$(".alternateStateErrorMsg").remove();
					j$(".alternateZipErrorMsg").remove();
				}
			});
		});  
    </script>

Open in new window


Thanks again for your help!  I sincerely appreciate it.
Will take a look shortly and revert.