【问题标题】:Function in onclick method not working - JAVASCRIPT NOT JQUERYonclick 方法中的功能不起作用 - JAVASCRIPT NOT JQUERY
【发布时间】:2015-09-06 17:41:29
【问题描述】:

我有一个表单,提交按钮不会执行被称为 onclick 的函数。

<form method="get" name="myform" onsubmit="return Validate()" style="margin: 100px">
  <input type="radio" id="Yes" name="Authorise" onclick="Clear_Message(Authorise_Message)"/>
    Yes
  <input type="radio" id="No" name="Authorise" onclick="Clear_Message(Authorise_Message)" />
    No
  <div class="Output" id="Authorise_Message"> </div>
  <input type="submit" id="SUBMIT" name="SUBMIT" onclick="Validator()"/>
</form>

验证器代码:

function Validator()
{
    //display an error message if radio button groups have no value, if it does have a value then clear the error message
    Title_Radio();
    Gender_Radio();
    Partnership_Radio();
    Communication_Radio();
    Authorise_Radio();
    Advice_Radio();
    CC_Radio();
    Switch();

    alert("This function was called");
}

无线电方法检查无线电是否有值,如果没有,则更改 Authorise_Method div 以在无线电旁边显示一条消息,

但该方法似乎不会执行。当我在&lt;input type="button" onclick="Validator"/&gt; 中使用它时,它似乎可以工作,但我需要它来提交,所以我将其更改为提交类型按钮......

【问题讨论】:

  • 你的意思是onClick="return Validator();"
  • 不,被调用的 onclick 函数纯粹是为了显示错误,但这会起作用吗??
  • 你阻止submitget机制吗?
  • 这是什么意思?我是 HTML 的初学者
  • 您的点击功能正在被触发,但由于它也有type="submit",所以它的提交也请参见output.jsbin.com/quyuke 进行演示。我认为它不是所需的功能。所以基本上你应该在提交函数中验证,而不是onClick

标签: javascript html function dom-events


【解决方案1】:

您应该为表单分配id,然后在提交表单之前在submit事件处运行您的代码,并在验证失败时阻止表单提交。

所以 html 应该是:

<form id="theForm" method="get" name="myform" style="margin: 100px">
    <input type="radio" id="Yes" name="Authorise" onclick="Clear_Message('Authorise_Message')"/> Yes
    <input type="radio" id="No" name="Authorise" onclick="Clear_Message('Authorise_Message')" /> No
    <div class="Output" id="Authorise_Message"></div>
    <input type="submit" id="SUBMIT" name="SUBMIT"/>
</form>

您应该将以下代码添加到您的 JavaScript 代码中:

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("theForm").addEventListener("submit", function(event) {
        Validator();
        //if the validation fails, prevent the form submission by calling the following function:
        //event.preventDefault();
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2016-09-02
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多