简体   繁体   中英

Basic jQuery contact form issue

I'm stuck writing jQuery validation for a contact form. I wrote a simple code which would check whether an input form contained any characters; if there are any characters then it may continue to run the PHP code and send me the email. Otherwise, show an error box telling the customer to double-check that. Here is the code:

    (function($){
       $('.required',$form).each(function(){
         var inputVal = $('form-element-name').val();
         var inputVal2 = $('form-element-email').val();

                if(inputVal == ''){
                    $('errorbox1').addClass('errormsg1');
                } 

                else if(inputVal2 == '') {
                    $('errorbox2').addclass('errormsg2');
                }
            }
     }

Inputval is the inputfield for the name and inputval2 is the inputfield for the e-mail. Furthermore, Errorbox1 is a container that is empty and the errormsg1 would be the class that would give the errorbox1 a background-image saying error.

Here is a jsFiddle .

It looks like you are missing the hash from your jQuery selectors - you should have $('#form-element-name') instead of $('form-element-name') - which will select elements based on their id.

Or - a dot to select by class instead.

You need to put your code inside the form's onsubmit event then return false; or use e.preventDefault(); to cancel the form submission.

$('#your-form-id').submit(function() {
    // if error then cancel form submission
});

$('errorbox1') and $('errorbox2')

should be

$('.errorbox1') and $('.errorbox2') if class selector

or

$('#errorbox1') and $('#errorbox2') if ID selector

Note the dot/# before the errorbox1.

Below are references to class and ID selector,

http://api.jquery.com/class-selector/

http://api.jquery.com/id-selector/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM