我在表单中输入了密码字段和两个按钮。第一个按钮用于密码确认,第二个按钮用于提交表单。
我想做的是,如果我单击密码确认按钮,然后单击提交按钮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>
答案 0 :(得分:2)
问题是在您确认密码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>
答案 1 :(得分:1)
您应该在输入密码上使用required attribute而不是仅仅依靠Javascript来检查它是否为空,因此您将不需要下面的if / else。
要解决这种情况,您只需要保存一个已确认密码的变量,然后检查该变量是否存在。
答案 2 :(得分:0)
您可以使用变量保存确认密码的状态。
Stack(
children: <Widget>[
SizedBox(
height: 20,
child: LinearProgressIndicator(
value: 0.6,
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
),
),
Align(child: Text("Text"), alignment: Alignment.topCenter,),
],
)
var isPwdConfirmed = false;
function confirmPassword() {
var cp = document.getElementById("user_pass");
if (cp.value == "") {
alert("Password please");
return false;
} else {
isPwdConfirmed = true;
document.getElementById("replace").innerHTML = "Hello World";
}
}
function submitForm() {
var cb = isPwdConfirmed;
if (cb != true) {
alert("Confirm password first!");
return false;
} else if (confirm("Are you sure?")) {
alert("Done!");
return false;
}
}