• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 515
  • Last Modified:

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

0
-Dman100-
Asked:
-Dman100-
  • 2
1 Solution
 
Scott Fell, EE MVEDeveloperCommented:
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.
0
 
Julian HansenCommented:
I don't understand your code

j$('[id$=documentQuantity]').each(function(index){

Implies more than one element with the same id?

Any particular reason you are using the ['id$=btnSubmit'] instead of $('#btnSubmit') ?

Then to your question - you have
            if(alternateAddress.attr("checked")) {

Then - if no error message is showing then add the error message after the element

                if(j$('.alternateStreetErrorMsg').length == 0) {

Where are you actually validating the fields?

I would have expected to see the error message being added only if a field did not validate?

Then I would instead have a flag $status = true - that I would set to false wherever a validation fails - and then return that value instead of the preventDefault.

If your handler returns false - it has the same effect
0
 
-Dman100-Author Commented:
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.
0
 
Julian HansenCommented:
Will take a look shortly and revert.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now