I'm using the following code to send some value from a textarea but first i want to ensure that the Textarea is not empty and then if not empty on keypress "Enter" then send the value to ajax.

The problem is value length counts line breaks and the validation fails. Another is line breaks, How do i prevent line breaks?

JAVASCRIPT

$(document).keypress(function(e) {
    if(e.which == 13) { 
        if ($('.msgInput').val().length < 2){
            alert ('No lol, your message is too short, type some more...')
        } else {
        var Msg = $('#Messageinput').val()

            $.ajax({
                type:"POST",
                data: {
                    data:Msg
                },
                url:"../websocket-example-821156/client.php"
            }).done(function(feedback){
                $('#NewMessagesHolder').prepend('<div class="MessageClass    ServerMessage">'+ '<span class="ChatName">Server ('+ time + ')</span>' + ':'+feedback+'</div>');
            })  

            var text = $('.msgInput').val();

            $('.msgInput').val("");
            $('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ text +'</div>')
        }
    } 
});
有帮助吗?

解决方案

You can use jQuery.trim to remove line breaks for start and end. This will make him at least put two characters. As with single character you would remove the line breaks and left with the character.

Live Demo

if ($.trim($('.msgInput').val()).length < 2){

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved, jQuery doc.

其他提示

$(document).keypress(function(e) {

    var text = $('.msgInput').val().replace(/\r\n/g,'\n').replace(/\n/g,'');

    if(e.which == 13) { 
        if (text.length < 2){
        alert ('No lol, your message is too short, type some more...')
       } else {
        var Msg = $('#Messageinput').val()
        $.ajax({
            type:"POST",
            data: {data:Msg},
            url:"../websocket-example-821156/client.php"
        }).done(function(feedback){
        $('#NewMessagesHolder').prepend('<div class="MessageClass ServerMessage">'+ '<span class="ChatName">Server ('+ time + ')</span>' + ':'+feedback+'</div>');
    })  

    $('.msgInput').val("")
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ text +'</div>')
    }
    } 
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top