我在表单中输入了密码字段和两个按钮。第一个按钮用于密码确认,第二个按钮用于提交表单。
我想做的是,如果我单击密码确认按钮,然后单击提交按钮window.confirm(),将显示并提交表单。

我使用javascript中的if/else语句尝试了此操作,但是当我单击确认按钮然后提交时,未显示window.confirm()



function confirmPassword() {
  var cp = document.getElementById("user_pass");
  if (cp.value == "") {
    alert("Password please");
    return false;
  } else {
    document.getElementById("replace").innerHTML = "Hello World";
  }
}

function submitForm() {
  var cb = document.getElementById("confirm_btn").click;
  if (cb != true) {
    alert("Confirm password first!");
    return false;
  } else if (confirm("Are you sure?")) {
    alert("Done!");
    return false;
  }
}

<form onsubmit="return submitForm()">
  <table>
    <td id="replace">
      <input type="password" id="user_pass">
      <button type="button" id="confirm_btn" onclick="confirmPassword()">Confirm</button><br>
    </td>
  </table>
  <button type="submit">Submit</button>
</form>

最佳答案

问题是确认密码var cb = document.getElementById("confirm_btn").click;后未定义。相反,您应该使用一些持久变量来查看密码是否已确认,如下所示。



var confirmed = false;

function confirmPassword() {
  var cp = document.getElementById("user_pass");
  if (cp.value == "") {
    alert("Password please");
    return false;
  } else {
    document.getElementById("replace").innerHTML = "Hello World";
    confirmed = true;
  }
}

function submitForm() {
  if (!confirmed) {
    alert("Confirm password first!");
    return false;
  } else if (confirm("Are you sure?")) {
    alert("Done!");
    return false;

  }
}

<form onsubmit="return submitForm()">
  <table>
    <td id="replace">
      <input type="password" id="user_pass">
      <button type="button" id="confirm_btn" onclick="confirmPassword()">Confirm</button><br>
    </td>
  </table>
  <button type="submit">Submit</button>
</form>

关于javascript - 如果单击按钮,则显示窗口确认并提交表单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58518073/

10-12 00:34
查看更多