我正在尝试编写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 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" );
}
});
}
答案 0 :(得分:1)
如果您希望像按钮这样的事件单击不遵循其默认行为,您可能需要尝试以下操作。在这种情况下,页面将不会重新加载:
$("#sendButton").click(function(event) {
if ($("#search").val() == "") {
event.preventDefault();
[...]
我想到的另一个提示是,您也可以考虑声明按钮的类型属性。这样做,该按钮不再具有默认行为:
<button id="sendButton" type="button">SEND</button>