php - 'onclick' 似乎没有调用带有 'submit' 按钮的函数

标签 php javascript html

我遇到过很多次(我不想在这里使用“输入类型按钮”)为什么哦为什么“onclick”不调用函数 check(); ?即使字段为空,页面仍会提交。感谢您的评论。

Javascript:

function check() { 
    var name =  document.getElementById('username_res');
    var passw_old =  document.getElementById('passw_reset_old');
    var passw_new =  document.getElementById('passw_reset');
    var button_res = document.getElementById('sub_res');

    if ((name.val() == "") && (passw_old.val().length == "") && (passw_new.val().length == "")) { 
        button_res.disabled = true; 
    } else {
        button_res.disabled = false;
    }
}

HTML:

<form id="passw_res" name="passw_res" method="post" action="pass_reset.php">
<fieldset style="width:300px"><br/>
<legend id="pass_legend" align="left">Password reset</legend><br/>
<input type="text" id="username_res" name="username_res" maxlength="50" />
<input type="password" id="passw_reset_old" name="passw_reset_old" maxlength="16"/>
  <input type="password" id="passw_reset" name="passw_reset" maxlength="16"  />
  <input type="submit" value="submit" id="sub_res" name="sub_res" onclick="check();"/>
 </fieldset>
  </form>

所以...页面不应该在空白字段上提交 - 为什么要提交?谢谢..

最佳答案

将你的函数改成这样:

function check() { 

    var name =  document.getElementById('username_res').value;
    var passw_old =  document.getElementById('passw_reset_old').value;
    var passw_new =  document.getElementById('passw_reset').value;

    return ((name != '') && (passw_old != '') &&  (passw_new != ''));

}

您实际上不必将 onclick 事件更改为 onsubmit,只需将其更改为 onclick="return check();"。您需要向 onclick 事件返回 false 以防止它被触发。

您可能希望添加一些视觉增强功能来指示未提交表单的原因。否则会使访问者感到困惑。

关于php - 'onclick' 似乎没有调用带有 'submit' 按钮的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7464478/

相关文章:

html - CSS 替换 YouTube 嵌入的黑条

html - 如何在 Bootstrap 中设置最小和最大宽度

java - 与 PHP 5.4 相比,Java Web 应用程序内存和 CPU 使用率有多高

php - 在 Drupal 中重新通知用户帐户

php - 删除并加入不起作用-Codeigniter

javascript - 注销时php语句导致 "500 - Internal server error"

javascript - Mongoose JS路径默认生成id

javascript - 找不到此依赖项: components/main/Footer in ./node_modules..../src/App.vue

javascript - 使用 Ajax/Javascript 增加 Rails 模型列

html - 在 Angular 应用程序中父级悬停在父级的下一个兄弟后面时显示绝对定位的 div(宽度大于父级)