AndrewLeonardi AndrewLeonardi - 5 months ago 14
jQuery Question

Cannot get === string.length to work correctly

I have code that checks if a user has entered text into an input field. If the field is empty I want to display: you have not started.

If the field has a length greater than 1 - I want to display: you've finished. My code below works for determining when the user is finished but displays nothing saying you have not started. Any thoughts? Thanks!

HTML:

<p id="progressDisplay"> </p>



<p id="response"> </p>
<p id="response2"> </p>


JS:

var progress =($("#progressDisplay").text());


if( progress.length === 0 ){
$("#response2").text("You have not entered anything yet")
}

if( progress.length > 1){
$("#response").text("You've Finished this section")
}

Answer

Whitespace in the element is included in its text value. Your element starts with a single whitespace character, so it always has a length > 0.

Trim the text to avoid whitespace, for that you can use native JavaScript String#trim method.

var progress = $("#progressDisplay").text().trim();

or use jQuery.trim() method.

var progress = $.trim($("#progressDisplay").text());