提交后如何更改提交按钮的操作

时间:2017-10-12 00:38:57

标签: javascript jquery html forms events

我希望在用户登录

后更改提交按钮以调出注销功能
<html>
<head>
 /* Here I have the links for jQuery and bootstrap so, they are working properly
</head>
<body>
<form onsubmit="signIn(event)">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit" id="connect_disconnect">
</form>
</body>

<script type="text/javascript">
  function signIn() {
    code ....
    // Below I just change the caption of the submit button from 'Connect' to 
    // 'Disconnect'
    $("#connect_disconnect").text('Disconnect');
    }
</script>

<script type="text/javascript">
  function signOut() {
    code...
    }
</script>

</html>

使用上面的代码,当我点击提交按钮时,即使我已经登录,它也会调用signIn函数。我希望它在我已经签名时调用signOut函数。有任何想法吗? 在此先感谢,如果我的问题不明确,请告诉我。

1 个答案:

答案 0 :(得分:0)

如果您对表单应用“submit”事件处理程序,则运行event.preventDefault()可以阻止表单提交本机方式,并且您可以运行任何所需的Javascript。

下面我添加了一个代码示例,展示了如何捕获事件。

我尽量不在我的答案中添加太多哲学,但我决定包含一个链接Javascript文件的示例。

HTML

<body>
  <form id="theForm">
    <input type="text" id="username" />
    <input type="password" id="password" />
    <input type="submit" id="connect_disconnect">
  </form>
  <script type="text/javascript" src="/script.js"></script>
</body>

Javascript(script.js)

(function() { // Create closure to avoid global-scoped variables

  var theForm = document.getElementById('theForm'); // Select the <form> element

  theForm.addEventListener('submit', handleFormSubmission); // Bind event listener.

  function handleFormSubmission(event) {
    event.preventDefault(); // Keep the form from taking any further native action

    if( /* user is signed in */ )
      signOut();
    else
      signIn();
  }

  function signIn() {
    // Sign In Code
  }

  function signOut() {
    // Sign Out Code
  }

})(); // End closure