使用提交按钮发送而不是回车键

时间:2013-04-17 12:15:06

标签: javascript html

我有这段代码

// watch textarea for release of key press
        $('#sendie').keyup(function(e) {
            if (e.keyCode == 13) {
                var text = $(this).val();
                var maxLength = $(this).attr("maxlength");
                var length = text.length;
                // send 
                if (length <= maxLength + 1) {
                    chat.send(text, name);
                    $(this).val("");
                } else {
                    $(this).val(text.substring(0, maxLength));
                }
            }
        });

当有人点击输入按钮时,它会将textarea中键入的消息发送到某个电子邮件地址。如何更改此项以使用提交按钮,如下面的代码?

< div id="page-wrap">
        < form id="send-message-area">
            < p>Your message: </p>
            < textarea id="sendie" maxlength = '100' placeholder ="Send Your Message">  < /textarea>
    < input type="submit">
        < /form>

    < /div>

2 个答案:

答案 0 :(得分:2)

请将代码附加到表单提交

$("#send-message-area").on("submit", function (e) {
    var elem = $("#sendie");
    var text = elem.val();
    var maxLength = parseInt(elem.attr("maxlength"),10);
    var length = text.length;
    // send 
    if (length <= maxLength + 1) {
            chat.send(text, name);
            elem.val("");
    } else {
            elem.val(text.substring(0, maxLength));
    }
    e.preventDefault();
});

答案 1 :(得分:1)

$("#send-message-area").on("submit", function (e) {
var text = $("#sendie").val();
var maxLength = $("#sendie").attr("maxlength");
var length = text.length;
// send 
if (length <= maxLength + 1) {
        chat.send(text, name);
    alert(text);
        $("#sendie").val("");
} else {
        $("#sendie").val(text.substring(0, maxLength));
}
e.preventDefault();
});

检查样本here