user2539077
user2539077

Reputation: 21

Append Text with conditional statement in Javascript

I'm new to Javascript. I'm creating a cell phone animation to illustrate probability. I have a graphic of an iPhone and buttons for all the keys. When a button is pressed the corresponding number shows on the phone screen (box I drew and ID as "phone"). However, there are some stipulations: for example, the 3-digit area code and 3-digit prefix cannot start with 1 (etc.). So I have conditions that must be met before the text can be appended. Here is my code for entering the number 1 when its button is pressed:

var phone = document.getElementById("phone");

if(phone.value.length == 0) {
phone.innerHTML = phone.innerHTML + "";
}

else if(phone.value.length == 6) {
phone.innerHTML = phone.innerHTML + "";
} 

else if(phone.value.length == 3) {
phone.innerHTML = phone.innerHTML + "1)";
} 

else if(phone.value.length == 8) {
phone.innerHTML = phone.innerHTML + "1-";
} 

else if(phone.value.length == 2) {
phone.innerHTML = phone.innerHTML + "";
} 
else {
phone.innerHTML = phone.innerHTML + "1";
} 

Unfortunately, this code doesn't work. If I comment out all the code except something like

var phone = document.getElementById("phone");
phone.innerHTML = phone.innerHTML + "1)";

then it works. So I am assuming I don't have the correct syntax for the conditionals. Thanks!

Upvotes: 2

Views: 2943

Answers (2)

Kilian Stinson
Kilian Stinson

Reputation: 2394

Due to your working example with innerHTML, phone is probably not an input element. So you have to use innerHTML instead of value in order to get the string and compare its length.

Replace

if (phone.value.length == 0)
....

with

if (phone.innerHTML.length == 0)
....

in your conditional statements.

Upvotes: 1

Rick Hoving
Rick Hoving

Reputation: 3575

Does this work?

var phone = document.getElementById("phone");
var addition = "";    

switch(phone.value.length){
   case: 0
   case: 6
       addition = "";
       break;
   case: 3
       addition = "1";
       break;
     .......//put rest of your cases here and dont forget default: break;
}


phone.innerHtml += addition;

The changes I have made:

  • In a case where you have this much else if statements, it is better to use the switch statement
  • I added a new variable addition which holds the string that has to be appended to the innerhtml of the phone, therefore you only have to change the innerHtml only once.

Upvotes: 0

Related Questions