简体   繁体   中英

Disable then re-enable button after AJAX Response

So I'm trying to disable a button while javascript is processing, then re-enable it when the javascript is done. The code below works in every browser I've tried except for IE7. In IE7 it just seems to ignore the disable and re-enable and looks like it's still enabled the whole time. So how can I get the correct behavior in IE7?

    <script>
      function doSomething()
      {
        document.getElementById("myButton").disabled = true;
        ...
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, false);
        xmlhttp.send(null);
        response = xmlhttp.responseText();

        if (response != "false")
        {
          document.getElementById("myButton").disabled = false;
        }
        ...
      }
    </script>
    <form onsubmit="doSomething(); return false;">
      <input type="submit" id="myButton" value="Do Stuff"/>
    </form>
    <div id="results"></div>

disabled is not a true/false toggle. If you want to enable something after it has been disabled you can remove the disabled attribute completely.

To set: document.getElementById("myButton").setAttribute("disabled","disabled");

To clear: document.getElementById("myButton").removeAttribute("disabled");

You'll need to put the disabled = false part in the ajax response handler:

function doSomething() {
  var btn = document.getElementById("myButton");
  btn.disabled = true;

  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);
  var response = xhr.responseText;

  // Test this stuff!
  alert(response);

  btn.disabled = false;

  // Test more!
  alert(btn.disabled);
}

So it was a redraw issue with IE7, so it wasn't redrawing until everything executed. So after more research and many attempts at getting IE to redraw when I wanted it to this was what finally worked, it's really hokey and I hope to find a better way to do it, but it works for now.

<script>
  function doSomething()
  {
    document.getElementById("myButton").disabled = true;
    setTimeout(doSomething2(), 1);
    return false;
  }

  function doSomething2()
  {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send(null);
    response = xmlhttp.responseText();
    document.getElementById("results).innerHtml = response;
    setTimeout(doSomething3(), 1);
    return false;
  }

  function doSomething3()
    document.getElementById("myButton").disabled = false;
    return false;
  }
</script>
<form onsubmit="doSomething(); return false;">
  <input type="submit" id="myButton" value="Do Stuff"/>
</form>
<div id="results"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM