开发者

Multiple jQuery Functions?

I have a chat on my site that runs on jQuery. However, the problem is that on IE9, when t开发者_C百科he user presses Enter on the input text field it submits twice. I am assuming that it may be thinking that it has to also click the button?

Any help?

<script>
$('#message').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13')
    {
        sendPostMessage();
    }
});

$('#sendMessage').click(function(event){
    if(this.disabled == true)
    {
        alert('meh');
    }
    var toSend = $('#message').val();
    if(toSend.length > 1 && toSend.length < 160)
    {
        sendPostMessage();
        //alert('You are sending a message.' + toSend);
    }
    else
    {
        alert('Invalid message.');
        this.disabled = true;
        window.setTimeout(function(){
            $('#sendMessage').removeAttr('disabled');
        }, 3000);
    }
});

jQuery.fn.compare = function(t) {
    if(this.length != t.length)
    {
        return false;
    }

    var a = this.sort(), b = t.sort();
    for(var i = 0; t[i]; i++)
    {
        if(a[i] !== b[i])
        { 
            return false;
        }
    }

    return true;
};

function sendPostMessage()
{
    $.post("http://www.prizetv.org/alpha/ajax.php", { "message": $('#message').val() }, function(data) {
            //alert(data);
            $('#message').val('');
        }
    );
}

var oldMessages;
var temp;
var scroll;

$(document).ready(function() {update();});



function update() { 
    $.getJSON("http://www.prizetv.org/alpha/ajax.php", function(json) {
        $("#actual").empty();

        jQuery.each(json, function(i, val) {
            var test = val[0] + "&nbsp;<b>" + val[1] + "</b>:&nbsp;" + val[2] + "<br />";
            $("#actual").append(test);
        });
        $("#actual").scrollTop(0);
    });

    setTimeout(update, 1000);
}
</script>


Call e.preventDefault() to prevent IE from handling the Enter keyrpess itself.


Clear #message when you post and not after the successful response. You'll probably want to handle a post error so that the message is repopulated.

function sendPostMessage()
{
    var msg = $('#message').val();
    $('#message').val('');
    $.post("http://www.prizetv.org/alpha/ajax.php", { "message": msg}, function(data) {
            //alert(data);
        }
    );
}

Update: I missed that you were not preventing the form from submitting due to pressing enter in an input field. You'll want to prevent the form from submitting with event.preventDefault(), when the user presses the enter key.

if(keycode == '13')
{
    sendPostMessage();
    event.preventDefault();
}


That is because enter triggers a submit of the form that the input is in as well as any handlers you may have.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜