javascript 表单的输入 type="submit" 似乎没有触发 onsubmit 处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15520057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:04:31  来源:igfitidea点击:

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

javascripthtmlformsvalidationonsubmit

提问by aminimalanimal

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

我试图通过 onsubmit 触发一个 javascript 函数来验证我的表单。

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.

我知道该函数本身可以工作,因为我可以在表单标记后立即在脚本标签中调用它,并且我收到我的 console.log 消息和它创建的错误消息出现在表单上。

The PHP validation itself works, but I've only been able to actually submit the form via javascript's .submitplaced 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".

PHP 验证本身有效,但我只能通过.submit放置在 div上的 javascript 实际提交表单。显然,因为这绕过了任何客户端验证,所以我不能那样做,因此我div id="submit"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 completely 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

我一直在查看其他示例,包括我过去自己编写的我知道工作的表单,并且似乎完全没有答案。这可能非常简单,出于某种原因,我在过去的 6 小时内无法也无法看到它。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 onSubmitor onsubmit... I don't know. I can't see what's wrong with this at all. Anyone?

我已经尝试了几次不同的迭代onsubmit="return validateForm();"- 带或不带分号,将其写为onSubmitonsubmit......我不知道。我根本看不出这有什么问题。任何人?

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).readyand is available globally as I've called it from within script tags directly following the form.

下面是要调用的函数onsubmitvalidateForm。它位于另一个文件中,但该文件始终包含在表单中,并且我已确保此函数不在其中$(document).ready并且在全局范围内可用,因为我已直接在表单后面的脚本标记中调用它。

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:

编辑 2:添加 PHP 验证/邮政编码:

<?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.com';
    } else {
        $subject = $field_name . ' has contacted you via thiswebsite.com';
    }

    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.

澄清一下——当我点击提交按钮时,完全没有任何反应。

回答by Lee Kowalkowski

Your jQuery is blocking the form submit here:

您的 jQuery 阻止了此处提交的表单:

//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.

我的意思是,当我调试您的站点并按下提交按钮时,我到达了return false;上面,之后事件处理结束。

回答by Kenneth Solberg

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.

什么都没有发生的原因是您使用了新的 html5 'pattern' 属性,该属性试图在您的输入到达您的验证函数之前对其进行正则表达式验证。删除模式属性并重试。