【问题标题】:Button enabled throughjs function goes back to disabled state通过js函数启用按钮回到禁用状态
【发布时间】:2021-10-20 14:47:36
【问题描述】:

我有一个带有两个按钮和一些 texareas 的表单。由于第二个只有在单击第一个后才可用,所以我将其设置为默认禁用,然后使用 js 函数调用启用它。这样可行。但是,当单击第一个按钮时,会执行一些 php 代码(通过 if(isset($_POST['submit'])){ if ($_SERVER["REQUEST_METHOD"] == "POST")) 并且在执行该 php 代码后,按钮将返回禁用状态。

任何想法为什么?我似乎在 php 完成后重新加载了整个表单,但我不知道为什么。

这里是按钮和js函数的代码:

<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" onclick="enableButton2()"/>
   
<input id="saveFile" class="button_text" type="submit" name="download" value="Download" disabled/>

<script>
    function enableButton2() {
        document.getElementById("saveFile").disabled = false;
    }
</script>

【问题讨论】:

  • 如果您在没有 AJAX 的情况下发布表单,则在提交表单后会重新加载整个页面,因此一切都会恢复到初始状态,请尝试删除第一个按钮的“type”属性并使用 AJAX 发出 POST 请求...如果您只想使用第二个按钮提交,请查看 preventDefault() 以防止表单提交。 function enableButton2(e) { e.preventDefault(); //---- YOUR AJAX POST HERE -- document.getElementById("saveFile").disabled = false; }
  • 从来没有用 AJAX 做过任何事情,所以如果可能的话我宁愿避免(我是一名网络工程师,这个网站只是为了输出一个脚本)。第二个按钮触发文件下载。但是,只有在您单击第一个按钮后,正确的文件才会出现。我正在尝试通过 php 变量在输入属性中插入“禁用”,但这似乎也不起作用: /> $button_disabled 设置为“disabled”并在单击 button1 后更改为“”。
  • 要执行您的 PHP,您必须发布您的表单,如果您在没有 ajax 的情况下发布您的表单,页面正在重新加载...

标签: javascript php html


【解决方案1】:

查看Fetch API 以使用第一个按钮发布您的表单,然后响应正常(意味着您的 php 已执行并返回某些内容),第二个按钮已启用,否则显示错误。

function enableButton2() {
  var form = new FormData(document.getElementById('form'));
  fetch("YOUR-URL", { //Edit YOUR-URL to your .php script
    method: "POST",
    body: form
  }).then(function(response) {
    if (response.ok) {
      //Put your code here if form successfully submitted
      document.getElementById('saveFile').disabled = false;
    } else {
      //Put your code here if form successfully submitted but return something else than HTTP 200 Status
      console.log('Network error');
    }
  }).catch(function(error) {
    //Put your code here if form unsuccessfully submitted
    console.log(error.message);
  });
}
<form action=# id="form">
  <input id="saveForm" class="button_text" name="submit" type="button" value="Submit" onclick="enableButton2()" />
  <input id="saveFile" class="button_text" type="submit" name="download" value="Download" disabled />
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多