[英]Javascript checking if textbox filled or checkbox checked and displaying a div
I have a button like this: 我有一个像这样的按钮:
input type="submit" name="continue" id="continue" value="CONTINUE" class="submitContact" />
Then for this button I am setting up a js that looks like this: 然后为这个按钮设置一个看起来像这样的js:
$('#continue').click(function() {
$('#storePickUp').change(function() { //catch checkbox
var $check = $(this),
$div = $check.parent();
if($check.prop('checked') || $('#shippingZipCode').val().length)
{
$('.checkoutForm').fadeIn(1000);
}
else {
document.getElementById(shippingZipCode).style.backgroundColor = '#FFFEAD';
}
});
});
What I try to do is check whether a textbox .shippingZipCode
is filled out or a checkbox is checked #storePickUp
, and if affirmative I display a div that has class .checkoutForm
. 我想做的是检查是否填写了文本框.shippingZipCode
或选中了#storePickUp
复选框,如果是,则显示具有类.checkoutForm
的div。
However, I cannot get it to work. 但是,我无法使其正常工作。 Does this js look ok? 这个js看起来还好吗?
Thanks! 谢谢!
Your click event is coming from a submit
typed input. 您的点击事件来自submit
输入。 So first things first, you must return false
to prevent it from posting and redirecting. 因此,首先,您必须return false
以防止其发布和重定向。
Secondly, your click event is only assigning a change event. 其次,您的点击事件仅分配一个更改事件。 The change event will issue its assigned callback when a change is made to the selected input, which may not be for some time, definitely shorted than the few milliseconds before the page posts. 更改事件将在对选定的输入进行更改时发出其分配的回调,该更改可能不会持续一段时间,肯定比页面发布之前的几毫秒短。
You are going to want to check for your values, then decide which action to take, and then return false in order to stop the post from happening. 您将要检查您的值,然后确定要采取的操作,然后返回false以阻止发布。
$('#continue').click(function() {
var $check = $('#storePickUp');//use reference to check for value immediately
var $div = $check.parent();
if($check.prop('checked') || $('#shippingZipCode').val().length)
{
$('.checkoutForm').fadeIn(1000);
}
else {
document.getElementById('shippingZipCode').style.backgroundColor = '#FFFEAD';
}
return false;//prevent form from posting
});
No need for the change function for the checkbox. 不需要复选框的更改功能。 Just check its state. 只需检查其状态即可。
$('#continue').click(function() {
var $check = $('#storePickUp'),
$div = $check.parent();
if($check.prop('checked') || $('#shippingZipCode').val().length) {
$('.checkoutForm').fadeIn(1000);
} else {
document.getElementById('shippingZipCode').style.backgroundColor = '#FFFEAD';
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.