Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements The Conditional Challenge Solution

How to control the user's input by evaluating empty string, numbers instead of words and space after the actual answer?

I was able to make the program but I want to know how can we improve the program by:

  1. Asking the user to enter the answer if he/she leaves the answer box empty. i.e. empty string

  2. Asking the user to enter the word instead of number and vice-versa. Example : What is the name of longest river? Answer: 3. Instead of calling it wrong answer; remind the user to enter word.

  3. Remove the space after the last character of the answer so that 'Nile' is same as 'Nile '. Some users type space after word unknowingly.

Thanks in advance.

1 Answer

YI LI
YI LI
4,094 Points

Hello,

  1. just check the string is empty "" or not and popup message ex. var str = document.getElementById("searchTxt").value; if(str == ""){ alert("The field is required"); return;//stop processing }
  2. There is typeOf operator to define the type of variable typeOf guid line, it can help you to know input is number or string
  3. try str.trim(), trim() remove spaces in the beginning and the end ex. " hello ".trim() will be "hello"

I am not sure these methods can solve your questions, hope they help!