jQuery验证后拒绝发布 [英] jQuery refuses to post after validation
问题描述
我已经在我的jQuery代码中添加了一些验证,以便在发布消息之前检查空白文本字段,但是它似乎无法正常工作.根本没有消息发布到我的墙上.知道我该如何解决吗?
I've added some validation to my jQuery code to check for blank text fields before it posts a message but it doesn't seem to be working. No messages are being posted at all to my wall. Any idea how I can fix this?
HTML
<div id="header">
<div class="container"> <span id="text_header">Virtual Idea Wall</span> </div>
</div>
<div id="main">
<div class="container">
<div id="chat"></div>
</div>
</div>
<div id="footer">
<div class="container">
<p>
<label for="title">Please give your idea a title</label>
<br />
<input type="text" id="title" name="title"/>
</p>
<p>
<label for="message">Please provide details of your idea</label>
<br>
<input type="text" id="message" name="message"/>
</p>
<p>
<input type="submit" id="sendmessage">
</p>
</input>
</div>
</div>
jQuery
jQuery(function ($) {
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function () {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message', '<b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val());
$messageTitle.val('');
$messageBox.val('');
}
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
});
推荐答案
您的click函数未传递事件"e",因此,当您调用"e.preventDefault()"时,该函数将停止运行.
Your click function is not passing in the event "e" so that would stop this from working when you make a call to "e.preventDefault()".
我做了这个jsfiddle-不支持套接字-但是它确实警告了我的消息. http://jsfiddle.net/4v2QT/
I made this jsfiddle - no socket support - but it does alert my message. http://jsfiddle.net/4v2QT/
这是唯一的更改(将e传递给函数)
This is the only change (the e passing into the function)
$messageForm.click(function (e) {
... code goes here!
}
这篇关于jQuery验证后拒绝发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!