Practice exercise - Booleans & if, else statements - 21. Height

Hi friends, the code I wrote below for the ‘Height’ exercise works by taking the input for the height in numbers only. It seems that the goal is to be able for the user to input the height (in numbers) and with the ‘cm’ words too, as stated here:

You should create a script that gives takes in a height in cm from the user

The limit for being low is about height <140 cm, and the limit for being high is about height> 190 cm.

If this is the case, how can we approach writing our if - else condition statements so that they work with a prompt or input field so they can take both numbers and words at the same time?

*Edit: I solved this by adding parseFloat() to the prompt and input variables.

Here’s the code:

 <h3>Height</h3>
 <p>Please enter your height:</p>
 <button id="btnHeight">Click me</button>

 <p id="printHeight"></p>

<script>
// Height - with button 

$(document).ready(function(){

 $("#btnHeight").click(function(){
  
 var height = parseFloat(prompt("Enter your height"));
 
  if(height < 140) {
     console.log("You're short!");
     document.getElementById("printHeight").innerHTML = "You're short!";
     document.getElementById("printHeight").style.color = "orange";
     
  }else if(height > 140 && height < 190){
       console.log("You're average!");
       document.getElementById("printHeight").innerHTML = "You're average!";
       document.getElementById("printHeight").style.color = "grey";    
     
  }else{
       console.log("You're tall!");
       document.getElementById("printHeight").innerHTML = "You're tall!";
       document.getElementById("printHeight").style.color = "MediumSeaGreen";
  } 
 });	
});
</script>
	
 <form id ="formHeight">	
  <input id="inputHeight" type="text" onfocus="this.value=''">
  <input type="submit" value="Submit">
 </form>

<script>
// Height - with input field

$(document).ready(function(){

 $("#formHeight").submit(function(){
  
 var height = parseFloat($("#inputHeight").val());
 
  if(height < 140) {
     console.log("You're short!");
     document.getElementById("printHeight").innerHTML = "You're short!";
     document.getElementById("printHeight").style.color = "orange";
     
  }else if(height > 140 && height < 190){
       console.log("You're average!");
       document.getElementById("printHeight").innerHTML = "You're average!";
       document.getElementById("printHeight").style.color = "grey";    
     
  }else{
       console.log("You're tall!");
       document.getElementById("printHeight").innerHTML = "You're tall!";
       document.getElementById("printHeight").style.color = "MediumSeaGreen";
  } 
	   event.preventDefault();
       var height = (""); 
 });	
});
</script>
1 Like