POST请求后禁用按钮

时间:2019-02-12 16:28:19

标签: javascript jquery

在发布请求后单击一次时,如何禁用按钮?在下面的代码中,当我单击按钮时,发布请求未执行,但按钮被禁用。

HTML

<form class="col s12" method="POST" action="<?php echo base_url(); ?>do/this">  

 <button type="submit" name="send" id="my_button" 
  class="waves-effect waves-green btn">My Button</button>

</form>

JS

document.getElementById("my_button").onclick = function() {
    this.disabled = true;   
}

2 个答案:

答案 0 :(得分:0)

如果我是你,我会使用jQuery来做到这一点。

喜欢:

    <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.post demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form action="/" id="searchForm">
  <input type="text" name="s" placeholder="Search...">
  <input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>

<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {

  // Stop form from submitting normally
  event.preventDefault();

  // Get some values from elements on the page:
  var $form = $( this ),
    term = $form.find( "input[name='s']" ).val(),
    url = $form.attr( "action" );

  // Send the data using post
  var posting = $.post( url, { s: term } );

  // Put the results in a div
  posting.done(function( data ) {
    var content = $( data ).find( "#content" );
    $( "#result" ).empty().append( content );
  });
});
</script>

</body>
</html>

您可以在代码的这一部分中禁用按钮:

posting.done(function( data ) {
    var content = $( data ).find( "#content" );
    $( "#result" ).empty().append( content );
  });

喜欢:

  posting.done(function( data ) {
        document.querySelector("#send_messages").disabled = true;
      });

答案 1 :(得分:0)

  document.getElementById("my_button").onclick = function(e) {
    e.preventDefault();
    this.disabled = true;
}
<form class="col s12" method="POST" action="<?php echo base_url(); ?>do/this">  

 <button type="submit" name="send" id="my_button" 
  class="waves-effect waves-green btn">My Button</button>

</form>