jquery检查搜索和消息字段中的输入
我正在尝试编写jquery代码,在提交按钮发送信息之前,检查消息输入区域是否已填写。如果未填写该字段,则会弹出警告框。如果已填写,则会弹出一个感谢提醒框jquery检查搜索和消息字段中的输入,jquery,Jquery,我正在尝试编写jquery代码,在提交按钮发送信息之前,检查消息输入区域是否已填写。如果未填写该字段,则会弹出警告框。如果已填写,则会弹出一个感谢提醒框 I can get an alert box to work with: if ($("#search").val() == "") alert ("Empty!"); but I can not get the alert boxes I created to pop up. Can anyone see where I am goin
I can get an alert box to work with: if ($("#search").val() == "") alert ("Empty!");
but I can not get the alert boxes I created to pop up. Can anyone see where I am going wrong?
HTML
<form id="contact" method="post" action="">
<!--search for person-->
<div>
<input type="text" id="search" name="search" placeholder=" Search for
User">
</div>
<button id="sendButton">SEND</button>
<div id="sendAlertText">
<p>Your message has been sent </p> <p id="sentCross">✖</p>
</div>
<div id="emptyAlertText">
<p>You need to complete all sections before you can send your
message</p> <p id="sentCross2">✖
</p>
</div>
</form>
CSS
#sendAlertText, #emptyAlertText {
display: none;
display:block;
position:relative;
margin: 0 20px;
z-index: 98;
height: 100px;
width: 250px;
background-color: red;
text-align: center;
font-size: 1.5em;
}
#sentCross {
position: absolute;
top: -20px;
right: 2%;
}
#emptyAlertText {
background-color: green;
}
JQuery
$(document).ready(function() {
// MESSAGE INPUT CAN NOT BE BLANK //
// Hide the alert messages
$("#sendAlertText").hide();
$("#emptyAlertText").hide();
$("#sendButton").click(function() {
if ($("#search").val() == "") {
$( "#emptyAlertText" ).fadeIn( "slow" );
} else {
$( "#sendAlertText" ).fadeIn( "slow" );
}
});
}
如果希望按钮单击之类的事件不遵循其默认行为,则可能需要尝试以下操作。在这种情况下,页面将不会重新加载:
$("#sendButton").click(function(event) {
if ($("#search").val() == "") {
event.preventDefault();
[...]
我刚刚想到的另一个暗示是,你也可以考虑声明按钮的类型属性。这样,按钮不再具有默认行为:
<button id="sendButton" type="button">SEND</button>
是页面重新加载的问题吗?可能是。对不起,我是初学者,如果我的页面正在重新加载,我如何解决这个问题?首先,你需要确认页面是否正在重新加载。如果不是,那就不是问题了。您好,页面正在重新加载,谢谢。我的else语句当前不起作用,因此将继续处理此问题。欢迎您的建议,非常感谢