简体   繁体   中英

How prevent line breaks in a text area and to stop Jquery from counting line breaks as values

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>')
    }
    } 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM