【问题标题】:Run Click JavaScript AFTER Form Validation表单验证后运行 Click JavaScript
【发布时间】:2015-10-21 22:50:05
【问题描述】:

我试图在验证并单击按钮后在按钮上运行 JavaScript 代码。我可以让代码在没有任何验证的情况下运行,但是当我在第 2 行添加“如果有效”时,JavaScript 根本不会运行,表单也不会提交。

这是正常工作的 JS,除了每次单击按钮时都会运行。我只想在表单有效时运行它。

<script>        
$('.subscribe-form-submit').click(function(){
        var $this = $(this);
        $(this).hide();
        $(this).after('<input type="button" disabled="disabled" class="btn btn-lg btn-primary subscribe-form-submit" value="Thanks!" />');
        return true;
        }
);
</script>

我试图添加一个如果有效的选择器,但是表单根本没有提交并且 JS 没有运行:

<script>
    $('.subscribe-form-submit').click(function(){
    if($('_form_1228').valid()) {
        var $this = $(this);
        $(this).hide();
        $(this).after('<input type="button" disabled="disabled" class="btn btn-lg btn-primary subscribe-form-submit" value="Thanks!" />');
        return true;
        }
});
</script>

这是我的表单,但我相信您需要的唯一信息是 ID 是“_form_1228”。

<form action='excluded' method='post' id='_form_1228' class="subscribe-form wow fadeIn" data-wow-duration="1s" role="form" accept-charset='utf-8' enctype='multipart/form-data' target="_blank">
<div class="form-validation alert"><!-- Validation Message here --></div>
<div class="form-group subscribe-form-input">
    <input type='hidden' name='f' value='1228'>
    <input type='hidden' name='s' value=''>
    <input type='hidden' name='c' value='0'>
    <input type='hidden' name='m' value='0'>
    <input type='hidden' name='act' value='sub'>
    <input type='hidden' name='nlbox[]' value='20'>
    <div id='compile999'>
        <input type="email" name="email" class="subscribe-form-email form-control form-control-lg" placeholder="Enter your email address" autocomplete="off" />
    </div>  
    <div id='_field1000'>
        <div id='compile1000'>
            <button class="subscribe-form-submit btn btn-black btn-lg" type="submit" data-loading-text="Loading...">Subscribe</button>
        </div>  
    </div>  
</div>

谢谢!

【问题讨论】:

  • 您的 JS 正在尝试验证名为 _form_1228 的标签,而不是带有 id=_form_1228 的表单。你的选择器应该是if ($('#_form_1228').valid()) {
  • 欢迎来到 StackOverflow。发布一个会随着时间而改变的网站的链接将使未来的访问者无法使用这个问题。相反,最好在 sn-p 中发布minimal, complete, and verifiable example
  • 感谢@DrewGaynor 我更新了代码并删除了指向我网站的链接。
  • @PaulRoub 你好,保罗。我做了你的改变,但它没有用,还有什么额外的想法吗?当我现在单击该按钮时,它不会执行任何操作。

标签: javascript jquery html validation


【解决方案1】:

您的选择器有问题... 见;

if($('_form_1228').valid()) {

应该是;

if($('#_form_1228').valid()) {

还有这个;

 if($this.hasClass('.subscribe-form-submit')){

应该是:

 if($this.hasClass('subscribe-form-submit')){

总而言之,当您使用 jquery 选择元素时,您使用 . (点)字符在你的类上,#(哈希)在你的元素 ID 上。但是,当您检查该元素是否具有具有 hasClass 函数的特定类时,您不应该使用 . (点)您的班级名称开头的字符。

【讨论】:

  • 我对表单 ID 选择器进行了更改,并删除了我使用 hasClass 执行的操作,但它不起作用。更新了上面的代码。任何想法
  • 你确定你已经包含了jquery验证插件吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 1970-01-01
  • 2015-12-04
  • 2014-11-20
相关资源
最近更新 更多