jquery .trim() with textboxes

12,710

Solution 1

As with lots of things in JavaScript (and programming in general), it's all about writing robust and maintainable code. This code is simply more tolerant of errant user input. If a user puts a space in there and then forgets about it, visually they won't be able to tell. This will take care of that scenario by checking to see if your field contains merely whitespace.

However, it might not be appropriate in all scenarios!

Further, as long as we're talking "robust and maintainable" code, be sure to use explicit equivalency operators rather than truthy/falsey tests:

$.trim($("#textboxid").val()) === ""

Solution 2

trim is so that if the user put in a space, it doesn't treat it like a value. Using trim with make a value of
" " become "".

Share:
12,710
Joseph
Author by

Joseph

Updated on June 04, 2022

Comments

  • Joseph
    Joseph almost 2 years

    In a different post I made, someome explained that to check for blank values in text boxes and textareas you should use .val() with $.trim to check for blank values. For e.g.,

    if($.trim($("#textboxid").val()) == "") {
        //do something
    }
    

    Can someone explain to me why we need to trim anything here? Are there hidden spaces or carriage returns in textboxes?