halid96
halid96

Reputation: 33

Check if input is blank

I want to check if input is blank or not. I am using simple code:

if ($("#logreg_content_input input").val().length > 0)

However this is not completely helping because user can enter spaces instead of characters. I want to remove spaces at the beginning and end of the input value entered by the user.

I tried this, but it is still counting spaces:

$.trim($("#logreg_content_input input"));
$("body").on("click", "#join_username_next", function() {
  $.trim($("#logreg_content_input input"));
  if ($("#logreg_content_input input").val().length < 21 && $("#logreg_content_input input").val().length >2) {
    alert("zaaaa");
    //AJAX 
  } else {
    if ($("#logreg_content_input input").val().length > 2){
      $('#logreg_content_input').attr("data-placeholder", "Too long.. max 20 chars") 
    } else {
      $('#logreg_content_input').attr("data-placeholder", "Username..(min 3 chars)(A-z, 0-9, space)")
    }; 
    $('#logreg_content_input input').focus();
  }
}); 

How can I remove the spaces first, and check the input value without counting intervals at beginning or end?

For example: If I have entered value: " Jessica " count the length as 7, not 9

Solution:
x = $("#logreg_content_input input").val().trim();
$("#logreg_content_input input").val(x);
after click.

Upvotes: 1

Views: 72

Answers (1)

Ankit Agarwal
Ankit Agarwal

Reputation: 30729

You can use this

if($("#logreg_content_input input").val().trim().length > 0)

instead of

if($("#logreg_content_input input").val().length > 0)

trim() removes the whitespace from the beginning and end of a string. In another words, it 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.

Upvotes: 2

Related Questions