Solved

how to bypass preventDefault method

Posted on 2014-04-10
4
491 Views
Last Modified: 2014-04-11
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
Comment
Question by:-Dman100-
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 53

Expert Comment

by:Scott Fell, EE MVE
ID: 39993371
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
 
LVL 57

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 39993853
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
 

Author Comment

by:-Dman100-
ID: 39994113
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
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 39994459
Will take a look shortly and revert.
0

Featured Post

Stressed Out?

Watch some penguins on the livecam!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question