0

Could anyone please tell me what I'm doing wron here? I'm sort of new to Javascript and I can't get this function to work the way i want it.. Basically if i type in ABCJ in the number1 field , i want to display 123X in the ansarea

<!DOCTYPE html>
<html>
<body>

<script>
function convert(number1)
{
     for(var i=0;i<number1.length();i++)
        {
      if(number1[i]=='A')
        {
            document.getElementById("ansarea").innerHTML="1";
        }
       else if(number1[i]=='B')
            {
            document.getElementById("ansarea").innerHTML="2";
        }
      else if(number1[i]=='C')
        {
            document.getElementById("ansarea").innerHTML="3";
        }
      else if(number1[i]=='D')
        {
            document.getElementById("ansarea").innerHTML="4";
        }
      else if(number1[i]=='E')
        {
            document.getElementById("ansarea").innerHTML="5";
        }
      else
            {
            document.getElementById("ansarea").innerHTML="x";
        }
    }
 }

</script>

<form>Enter here : <input type="text" name="number1"><br></form>

<button type="button" onclick="convert("number1")">Convert</button>

<div id="ansarea"><input type="text" name = "ans"></div>

</body>

</html>
7
  • 1
    use switch-case statements! Commented Mar 26, 2014 at 23:15
  • is using if else statements in this case wrong ? Commented Mar 26, 2014 at 23:17
  • i'm only trying to learn.. this isn't for any project i am working on.. just want to learn how to write and call basic functions in javascript :) Commented Mar 26, 2014 at 23:17
  • not wrong, but very very very ugly :) Commented Mar 26, 2014 at 23:17
  • 1
    Right now you are overwriting document.getElementById("ansarea").innerHTML every time, so you will never end up with 4 characters in there. You have to do something like document.getElementById("ansarea").innerHTML= document.getElementById("ansarea").innerHTML + "yournewstuffhere"; Commented Mar 26, 2014 at 23:17

4 Answers 4

1

this will make you code work...

<!DOCTYPE html>
<html>
<body>

<script>
function convert() {
    var valu = document.getElementById("some").value;
    document.getElementById("ansarea").innerHTML = "";
    for (var i = 0; i < valu.length; i++) {
        if (valu[i] == 'A') {
            document.getElementById("ansarea").innerHTML += "1";
        } else if (valu[i] == 'B') {
            document.getElementById("ansarea").innerHTML += "2";
        } else if (valu[i] == 'C') {
            document.getElementById("ansarea").innerHTML += "3";
        } else if (valu[i] == 'D') {
            document.getElementById("ansarea").innerHTML += "4";
        } else if (valu[i] == 'E') {
            document.getElementById("ansarea").innerHTML += "5";
        } else {
            document.getElementById("ansarea").innerHTML += "x";
        }
    }
}
</script>

<form>Enter here : <input type="text" name="number1" id="some"><br>

<button type="button" onclick="convert()">Convert</button>

<div id="ansarea"></div>
</form>

</body>

</html>

enter image description here

you dont need to pass a value to convert() since you are getting the value from the input field, you dont need the other input field, since you putting the text in a div..

Sign up to request clarification or add additional context in comments.

Comments

1

This is another working example:

<!DOCTYPE html>
<head>
<script>
function convert()
{

     var number1 = document.getElementById('textbox_id').value;

     for(var i=0;i<number1.length;i++)
        {
      if(number1.charAt(i)=='A')
        {
            document.getElementById("ansarea").innerHTML +="1";
        }
       else if(number1.charAt(i)=='B')
            {
            document.getElementById("ansarea").innerHTML +="2";
        }
      else if(number1.charAt(i)=='C')
        {
            document.getElementById("ansarea").innerHTML +="3";
        }
      else if(number1.charAt(i)=='D')
        {
            document.getElementById("ansarea").innerHTML +="4";
        }
      else if(number1.charAt(i)=='E')
        {
            document.getElementById("ansarea").innerHTML +="5";
        }
      else
            {
            document.getElementById("ansarea").innerHTML +="x";
        }
    }
 }

</script>
</head>
<body>
Enter here : <input type="text" name="number1" id='textbox_id'>
</br>

<button type="button" onclick="convert()">Convert</button>

<div id="ansarea"></div>

</body>

</html>

Few things to notice here:

  • You can take the value from inside the function convert()
  • You don't need the second onpening <html> tag after <!DOCTYPE html>
  • It's better not to skip the <head> tag
  • For this task specifically you don't need <form> so I've removed it, but you can add it if you plan to submit to some other method or something...

Comments

1

First, welcome to javascript ! Because you are starting, a good rule of thumb to start is to find your way around repetitions.

Here's another example on how you can execute exactly the same thing as in the other answers using a map:

// let's map all the characters you need against some digits
// this will make it super easy to add, remove or swap things around.
var map = { A: '1', B: '2', C: '3', D: '4', E: 5 };

// for example, map['A'] will now have the value of '1'

// we can store the output element once for good, 
// so you don't have to look it up over and over again. 
var outputElement = document.getElementById('ansarea'); 

function convert( inputString ) {

    // the result variable will temporary store the result, so let's start empty
    var result = "";

    for ( var i = 0; i < inputString.length; i ++ ) {

        // grab the current character so we don't have to look it up twice
        var char = inputString[i];

        if ( typeof map[char] !== 'undefined' ) {

            // cool, the character existed within the map. 
            // We can append its value to the result:
            result += map[char];

        } else {

            // ... if not add 'x'
            result += 'x';
        }
    }
    // and finally, populate the HTML with the result
    outputElement.innerHTML = result;
}

Comments

0

innerHTML - it is property containing html in element. And every time you completely rewriting it. Try this: document.getElementById("ansarea").innerHTML+="1"; document.getElementById("ansarea").innerHTML+="2"; // etc By += (instead =) you will concatenate old value with new.

And you must change you function call. Try this (i don't test it):

 function convert(selector) {
    var dataFromInput = document.querySelector(selector);
    var dataLength = dataFromInput.length();

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

    for(var i = 0; i < dataLength; i++) {

        switch (dataFromInput[i]) {
            case 'A':
                ansarea.innerHTML += '1';
                break;
            case 'B':
                ansarea.innerHTML += '2';
                break;
            case 'C':
                ansarea.innerHTML += '3';
                break;
            case 'D':
                ansarea.innerHTML += '4';
                break;
            case 'E':
                ansarea.innerHTML += '5';
                break;
            default:
                ansarea.innerHTML += 'x';
        }
    }
}

and add id for input:

<form>Enter here : <input type="text" name="number1" id="number1"><br></form> <button type="button" onclick="convert('#number1')">Convert</button>

5 Comments

Tried that but its still not writing the answer in to the box like i want it to .. am i calling the function correctly ?
@ps01 no. You trying to call it: onclick="convert("number1")" it is not right. First you used same quates. Try single quates: onclick="convert('ABCJ')" But if you want take value from input, you should get it from input first.
The input is called number1 // <form>Enter here : <input type="text" name="number1"><br></form>
@ps01 you can add id to input, like: <form>Enter here : <input type="text" id="my-form-input" name="number1"><br></form> and then you can get value of this input: var data = document.querySelector('#my-form.input').value; Look here: developer.mozilla.org/en-US/docs/Web/API/document.querySelector
@ps01, yes it is wrong. You must call your function with value from input, but not with 'number1' string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.