当我单击提交时,如果我的密码1和2不匹配,我试图使表格不重新加载。我的代码有什么问题,附加了html和js。
<label for="password">Lösenord: </label>
<input type="password" class="form-control" id="password" name="password" placeholder="Lösenord" required>
<p>
</p>
<label for="password2">Upprepa Lösenord: </label>
<input type="password" class="form-control" id="password2" name="password2" placeholder="Lösenord" required>
<p>
</p>
$(document).ready( function() {
$("#submit").click( function() {
var password1 = $("#password");
var password2 = $("#password2");
alert(password2);
if (password1 /= password2) {
preventDefault();
}
});
});
更新:尝试更改为“!=”和passwor.val(),仍然无法正常工作。
答案 0 :(得分:0)
如果我没记错的话,您只会获得对DOM元素的引用。要获取值,您需要使用.val()
您也在进行除法而不是比较。您的if语句比较应为:
if (password1.val() !== password2.val()) {
您还需要在您的点击监听器上传递事件对象。所以总的来说,应该是:
$("#submit").click( function(event) {
var password1 = $("#password").val();
var password2 = $("#password2").val();
if (password1 !== password2) {
event.preventDefault();
}
});
答案 1 :(得分:0)
将点击事件附加到preventDefault()
的一部分,
在示例中应使用简单的逻辑比较器!=
,因为它与对象类型无关,最终如果字段为空,则阻止真正的验证
$("#submit").click( function(event) {
var password1 = $("#password").val().length>0 ? $("#password").val() : 'a';
var password2 = $("#password2").val().length>0 ? $("#password2").val() : 'b';
//prevent true if empty
if (password1 != password2) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form id="form" action="">
<label for="password">Lösenord: </label>
<input type="password" class="form-control" id="password" name="password" placeholder="Lösenord" required>
<p>
</p>
<label for="password2">Upprepa Lösenord: </label>
<input type="password" class="form-control" id="password2" name="password2" placeholder="Lösenord" required>
<p>
<button id="submit">Ok</button>
</p>
</form>
答案 2 :(得分:0)
除了@Joshua Robles指出的问题之外,
向您的输入字段添加一个空的value
属性,如下所示:
<input type="password" class="form-control" id="password" name="password" placeholder="Lösenord" value="" required>
完整代码和演示:
$("#submit").click( function(event) {
var password1 = $("#password").val();
var password2 = $("#password2").val();
if (password1 !== password2) {
alert("Passwords don't match")
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="password">Lösenord: </label>
<input type="password" class="form-control" id="password" name="password" placeholder="Lösenord" value="" required>
<p></p>
<label for="password2">Upprepa Lösenord: </label>
<input type="password" class="form-control" id="password2" name="password2" placeholder="Lösenord" value="" required>
<p></p>
<input type="submit" id="submit">