最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Form's input type="submit" does not seem to trigger the onsubmit handler - Stack Overflow

programmeradmin1浏览0评论

I am attempting to trigger a javascript function via onsubmit to validate my form.

I know that the function itself works because I can call it within script tags immediately after the form's markup and I receive my console.log message and the error messages it creates appear on the form.

The PHP validation itself works, but I've only been able to actually submit the form via javascript's .submit placed upon a div. Obviously because this bypasses any client-side validation, I can't leave it that way, thus I've replaced my div id="submit" with an input type="submit".

I've been looking at other examples, including forms I've coded myself in the past that I know work, and seem pletely out of answers. This is probably insanely easy, and for some reason, I just can't and haven't been able to see it for the last 6 hours. o_O

Here is my form's markup:

<form name="emailus" id="emailus" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validateForm();">
    <a href="mailto:[email protected]">
        <h3><i class="icon-envelope-alt icon-large"></i>Send us an email<span>: [email protected]</span></h3>
    </a>

    <div class="half">
        <fieldset class="name">
            <label for="cf_name"><h4>Name <span>*</span></h4></label>
            <input type="text" name="cf_name" class="textualformfield" alt="Jane Doe" pattern="^[a-zA-Z'\s]+$">
        </fieldset>
        <fieldset class="emailaddress">
            <label for="cf_email"><h4>E-mail <span>*</span></h4></label>
            <input type="text" name="cf_email" class="textualformfield" alt="[email protected]" pattern="{long string of regex}">
        </fieldset>
        <fieldset class="phonenumber">
            <label for="cf_phonenumber"><h4>Phone</h4></label>
            <input type="tel" name="cf_phonenumber" class="textualformfield" alt="555-555-5555">
        </fieldset>
        <fieldset class="eventdate">
            <label for="cf_eventdate"><h4>Event Date</h4></label>
            <input type="text" name="cf_eventdate" class="textualformfield" alt="May 25th, 2012">
        </fieldset>
        <fieldset class="location">
            <label for="cf_location"><h4>Location</h4></label>
            <input type="text" name="cf_location" class="textualformfield" alt="The Church">
        </fieldset>
    </div>

    <div class="half">
        <textarea name="cf_message" class="textualformfield" alt="Your Message"></textarea>
    </div>

    <input type="submit" for="emailus" name="submit" id="submit" value="Submit">
</form>

I've attempted several different iterations of onsubmit="return validateForm();"—with or without the semicolon, writing it as onSubmit or onsubmit... I don't know. I can't see what's wrong with this at all. Anyone?

Below is the function to be called onsubmit, validateForm. It is located in another file, but the file is always included when the form is, and I've made sure this function is not within $(document).ready and is available globally as I've called it from within script tags directly following the form.

var validateForm = function() {
    var valid = true;

    jQuery('p.validationhelpers').remove();

    if (document.emailus.cf_email.value == "" || document.emailus.cf_email.value == "[email protected]") {
        jQuery('.emailaddress').append("<p class='validationhelpers'>Please enter an email address.</p>");
        jQuery('.emailaddress>input').focus();
        valid = false;
    }

    if (document.emailus.cf_name.value == "" || document.emailus.cf_name.value == "Jane Doe") {
        jQuery('.name').append("<p class='validationhelpers'>Please enter your name.</p>");
        jQuery('.name>input').focus();
        valid = false;
    }
    console.log("I was triggered");

    return valid;
}

Edit 2: Added PHP Validation/Post code:

<?php if (!empty($_POST) ) { 
    $field_name = $_POST['cf_name'];
    $field_email = $_POST['cf_email'];
    $field_phone = $_POST['cf_phonenumber'];
    $field_eventdate = $_POST['cf_eventdate'];
    $field_location = $_POST['cf_location'];
    $field_message = $_POST['cf_message'];

    $mail_to = '[email protected]';

    //final attempt at validation or email submission preventation
    if ($field_name == "Jane Doe" || empty($field_name) || $field_email == "[email protected]" || empty($field_email)) {
        return false;
    }


    if (!($field_eventdate == "May 25th, 2012") && !empty($field_eventdate) && !($field_name == "Jane Doe") && !empty($field_name)) {
        $subject = 'Request for '.$field_date. ' from '.$field_name . 'via thiswebsite';
    } else {
        $subject = $field_name . ' has contacted you via thiswebsite';
    }

    if (!($field_name == "Jane Doe") && !empty($field_name)) {
        $body_message = 'Client\'s Name: '.$field_name."\n\n";
    }
    if (!($field_email == "[email protected]") && !empty($field_email)) {
        $body_message .= 'E-mail: '.$field_email."\n\n";
    }
    if (!($field_phone == "555-555-5555") && !empty($field_phone)) {
        $body_message .= 'Phone: '.$field_phone."\n\n";
    }
    if (!($field_eventdate == "May 25th, 2012") && !empty($field_eventdate)) {
        $body_message .= 'Event Date: '.$field_eventdate."\n\n";
    }
    if (!($field_location == "The Church") && !empty($field_location)) {
        $body_message .= 'Location: '.$field_location."\n\n";
    }
    if (!($field_message == "Your Message") && !empty($field_message)) {
        $body_message .= 'Message: '. "\n".$field_message;
    }

    $headers = 'From: '.$field_email."\r\n";
    $headers .= 'Reply-To: '.$field_email."\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

    $body_message = stripslashes($body_message);

    if ($mail_status) { ?>
        <script language="javascript" type="text/javascript">
            jQuery(document).ready(function () {
                jQuery('#contactus').before("<hr class='confirmationhelpers'><p class='confirmationhelpers'>Your e-mail has been sent!<br/>Thank you! We'll contact you shortly.</p><hr class='confirmationhelpers'>");
            });
        </script>
    <?php
    }
    else { ?>
        <script language="javascript" type="text/javascript">
            jQuery(document).ready(function () {
                alert('It seems there\'s been an error. Please, send an email to [email protected] to request your appointment.');
            });
        </script>
    <?php
    }
}

?>

Just to be clear—when I click the Submit button, absolutely nothing happens.

I am attempting to trigger a javascript function via onsubmit to validate my form.

I know that the function itself works because I can call it within script tags immediately after the form's markup and I receive my console.log message and the error messages it creates appear on the form.

The PHP validation itself works, but I've only been able to actually submit the form via javascript's .submit placed upon a div. Obviously because this bypasses any client-side validation, I can't leave it that way, thus I've replaced my div id="submit" with an input type="submit".

I've been looking at other examples, including forms I've coded myself in the past that I know work, and seem pletely out of answers. This is probably insanely easy, and for some reason, I just can't and haven't been able to see it for the last 6 hours. o_O

Here is my form's markup:

<form name="emailus" id="emailus" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validateForm();">
    <a href="mailto:[email protected]">
        <h3><i class="icon-envelope-alt icon-large"></i>Send us an email<span>: [email protected]</span></h3>
    </a>

    <div class="half">
        <fieldset class="name">
            <label for="cf_name"><h4>Name <span>*</span></h4></label>
            <input type="text" name="cf_name" class="textualformfield" alt="Jane Doe" pattern="^[a-zA-Z'\s]+$">
        </fieldset>
        <fieldset class="emailaddress">
            <label for="cf_email"><h4>E-mail <span>*</span></h4></label>
            <input type="text" name="cf_email" class="textualformfield" alt="[email protected]" pattern="{long string of regex}">
        </fieldset>
        <fieldset class="phonenumber">
            <label for="cf_phonenumber"><h4>Phone</h4></label>
            <input type="tel" name="cf_phonenumber" class="textualformfield" alt="555-555-5555">
        </fieldset>
        <fieldset class="eventdate">
            <label for="cf_eventdate"><h4>Event Date</h4></label>
            <input type="text" name="cf_eventdate" class="textualformfield" alt="May 25th, 2012">
        </fieldset>
        <fieldset class="location">
            <label for="cf_location"><h4>Location</h4></label>
            <input type="text" name="cf_location" class="textualformfield" alt="The Church">
        </fieldset>
    </div>

    <div class="half">
        <textarea name="cf_message" class="textualformfield" alt="Your Message"></textarea>
    </div>

    <input type="submit" for="emailus" name="submit" id="submit" value="Submit">
</form>

I've attempted several different iterations of onsubmit="return validateForm();"—with or without the semicolon, writing it as onSubmit or onsubmit... I don't know. I can't see what's wrong with this at all. Anyone?

Below is the function to be called onsubmit, validateForm. It is located in another file, but the file is always included when the form is, and I've made sure this function is not within $(document).ready and is available globally as I've called it from within script tags directly following the form.

var validateForm = function() {
    var valid = true;

    jQuery('p.validationhelpers').remove();

    if (document.emailus.cf_email.value == "" || document.emailus.cf_email.value == "[email protected]") {
        jQuery('.emailaddress').append("<p class='validationhelpers'>Please enter an email address.</p>");
        jQuery('.emailaddress>input').focus();
        valid = false;
    }

    if (document.emailus.cf_name.value == "" || document.emailus.cf_name.value == "Jane Doe") {
        jQuery('.name').append("<p class='validationhelpers'>Please enter your name.</p>");
        jQuery('.name>input').focus();
        valid = false;
    }
    console.log("I was triggered");

    return valid;
}

Edit 2: Added PHP Validation/Post code:

<?php if (!empty($_POST) ) { 
    $field_name = $_POST['cf_name'];
    $field_email = $_POST['cf_email'];
    $field_phone = $_POST['cf_phonenumber'];
    $field_eventdate = $_POST['cf_eventdate'];
    $field_location = $_POST['cf_location'];
    $field_message = $_POST['cf_message'];

    $mail_to = '[email protected]';

    //final attempt at validation or email submission preventation
    if ($field_name == "Jane Doe" || empty($field_name) || $field_email == "[email protected]" || empty($field_email)) {
        return false;
    }


    if (!($field_eventdate == "May 25th, 2012") && !empty($field_eventdate) && !($field_name == "Jane Doe") && !empty($field_name)) {
        $subject = 'Request for '.$field_date. ' from '.$field_name . 'via thiswebsite.';
    } else {
        $subject = $field_name . ' has contacted you via thiswebsite.';
    }

    if (!($field_name == "Jane Doe") && !empty($field_name)) {
        $body_message = 'Client\'s Name: '.$field_name."\n\n";
    }
    if (!($field_email == "[email protected]") && !empty($field_email)) {
        $body_message .= 'E-mail: '.$field_email."\n\n";
    }
    if (!($field_phone == "555-555-5555") && !empty($field_phone)) {
        $body_message .= 'Phone: '.$field_phone."\n\n";
    }
    if (!($field_eventdate == "May 25th, 2012") && !empty($field_eventdate)) {
        $body_message .= 'Event Date: '.$field_eventdate."\n\n";
    }
    if (!($field_location == "The Church") && !empty($field_location)) {
        $body_message .= 'Location: '.$field_location."\n\n";
    }
    if (!($field_message == "Your Message") && !empty($field_message)) {
        $body_message .= 'Message: '. "\n".$field_message;
    }

    $headers = 'From: '.$field_email."\r\n";
    $headers .= 'Reply-To: '.$field_email."\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

    $body_message = stripslashes($body_message);

    if ($mail_status) { ?>
        <script language="javascript" type="text/javascript">
            jQuery(document).ready(function () {
                jQuery('#contactus').before("<hr class='confirmationhelpers'><p class='confirmationhelpers'>Your e-mail has been sent!<br/>Thank you! We'll contact you shortly.</p><hr class='confirmationhelpers'>");
            });
        </script>
    <?php
    }
    else { ?>
        <script language="javascript" type="text/javascript">
            jQuery(document).ready(function () {
                alert('It seems there\'s been an error. Please, send an email to [email protected] to request your appointment.');
            });
        </script>
    <?php
    }
}

?>

Just to be clear—when I click the Submit button, absolutely nothing happens.

Share Improve this question edited Mar 20, 2013 at 11:53 aminimalanimal asked Mar 20, 2013 at 9:45 aminimalanimalaminimalanimal 4492 gold badges6 silver badges13 bronze badges 12
  • could you post your on submit() – Ezhil V Commented Mar 20, 2013 at 9:53
  • Try and remove the use of return on the onsubmit value, and simply put validateForm(), or, better yet: validateForm(); return false; in case the former does not return a truthy or falsy value. By the way, what's the use of for on the submit input? – Eliran Malka Commented Mar 20, 2013 at 9:56
  • 1 ensure that your validateForm() return true on successful validation – Ezhil V Commented Mar 20, 2013 at 9:58
  • first of all remove the for attribute in the input[type=submit], checking the javascript code should be next step, but make sure there isn't any javascript mand preventing the submission since you are expecting a submission. – w3jimmy Commented Mar 20, 2013 at 10:31
  • @javapirate is the validateForm function what you meant for me to post? Or are you referring to the PHP's portion? – aminimalanimal Commented Mar 20, 2013 at 10:39
 |  Show 7 more ments

2 Answers 2

Reset to default 2

Your jQuery is blocking the form submit here:

//this hides the contact form if the overlay is clicked. children is there to prevent the children from also having this effect.
    $('.overlay_vertical_align').click(function() {
        $('.grey_overlay').fadeOut('slow');
    }).children().click(function(e) {
        return false;
    });

I mean, when I debug your site, and press the submit button, I reach the return false; above, after which the event processing is over.

The reason nothing happens is that you use the new html5 'pattern' attribute which tries to regex validate your input before it even reaches your validate function. Remove the pattern attribute and try again.

发布评论

评论列表(0)

  1. 暂无评论