Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: $.trim() spaces between words in input.val()

I've seen some similar questions to mine here, but they don't really answer me...

So I'm doing this: (Inside the document ready function)

$("#dest").focusin(function() {
    $("#dest").val($.trim($("#dest").val()));
});

The ideia is when the user focus on a input called #dest trim all the space characters on it (previously added using focusout for visual comfort).

Right now, nothing is happening. :(

Hope someone can help me a bit here.

Thanks!


Is this a computer related problem? I've tested all the code provided by commenters and none works. I'm using Firefox and Safari under OSX (Snow Leopard) 10.6.8 and also Safari under 10.8.2 (Lion) and I got the same results... OSX problem? -- Everything is ok, check my last edit!


Final Edit and Solution thanks to Phil Klein

My problem was using incorrectly jQuery's trim() function... According to the trim() documentation it does the following:

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.

Yesterday I didn't read the last part where it says from the beginning and end of the supplied string -- Sorry everyone. :(

Lucky and after the drawing above, @Phil Klein understood my mistake and helped me with a solution:

$(function() {
    $("#dest").on("focus", function() {
        var dest = $(this);
        dest.val(dest.val().split(" ").join("")); 
    });
});

You can read more about the solution and see an example here.

Thanks to @Phil Klein and also everyone who helped me on this one ;)

like image 434
TCB13 Avatar asked Dec 20 '11 04:12

TCB13


2 Answers

The example below removes all spaces from the contents of the textbox on focus. This particular example requires jQuery 1.7+ since it uses the new .on() API:

$(function() {
    $("#dest").on("focus", function() {
        var dest = $(this);
        dest.val(dest.val().split(" ").join("")); 
    });
});

See this example: http://jsfiddle.net/RnZ5Y/5/

like image 194
Phil Klein Avatar answered Oct 14 '22 00:10

Phil Klein


Try these : $.trim($("#dest").val());
correct me if i am wrong !!

like image 39
Jigar Tank Avatar answered Oct 13 '22 23:10

Jigar Tank