1

I have a problem creating a for-loop using Javascript. It seems everyting is fine for me but still I didn't get what I want.

Take a look please to this code to understand more:

  • The HTML form code:

    <form name="myform">
        <textarea name="inputtext" cols="100%" rows="10%"></textarea><br />
        <input type="radio" name="options" value="javascript" checked> Option1 <br />
        <input type="radio" name="options" value="windows"> Option2<br />
        <input type="button" value="Do it" onClick="generate();"><br />
        <textarea name="outputtext" cols="100%" rows="10%"></textarea><br />
    </form>
    
  • The Javascript code:

    function generate() {
    var code = ""+document.myform.inputtext.value;
    if (document.myform.options[0].checked) {
        document.myform.outputtext.value = escape(code);
    }
    else {
        var result= "2- ";
        for(int i=0; i<code.length; i++) {
        //There will be some logic to decide if to add the char or not.
        result+=code.charAt(i);
        }
        document.myform.outputtext.value = result;
    }
    }
    

The problem is not clear for me. However, when I try to comment out the for-loop, everything works fine !

Any ideas?

1
  • int is not a datatype in javascript. Please use a javascript debugger (like firebug on firefox) to help you out. Commented May 15, 2011 at 19:26

2 Answers 2

8

There is no int data type in Javascript (or any data types at all used to declare variables).

for(var i=0; i<code.length; i++) {
Sign up to request clarification or add additional context in comments.

2 Comments

OMG! How I miss that ! Sometimes you mix between Java and Javascript. Thanks @Guffa :)
@2rk: I have the same problem jumping between C# and Javascript. I have done the exact same error several times. :)
0

There is also an Object-oriented solution to this.

var generate = {
   loop: function() {
        var code = ""+document.myform.inputtext.value;

        if (document.myform.options[0].checked) {
            document.myform.outputtext.value = escape(code);
        }
        else {
            var result= "2- ";
            //CHANGE THE INT(I assume Java) DATATYPE TO A LOCAL VARIABLE USING THE var KEYWORD TO KEEP THE SCOPE IN THE FOR LOOP
            //RECURSION CAN BE QUICKER
            for(var i=0; i<code.length; i++) {
            //There will be some logic to decide if to add the char or not.
            result+=code.charAt(i);
        }
        document.myform.outputtext.value = result;
     }
 }

generate.loop();

1 Comment

You forgot the closing bracket for the loop.

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.