0

I am newbie in javascript, I want to do looping normally use "for". I would like to duplicate this script about 10 ... how loop this script?

function getComboMotif1() {
    $.get("file.php?opt1=" + $("#id1"), function (data) {
        $("#asd1").html(data);
    });
}

The manual Loop script like this !!

function getww1() {
    $.get("file.php?opt1=" + $("#id1"), function (data) {
        $("#asd1").html(data);
    });
}

function getww2() {
    $.get("file.php?opt1=" + $("#id2"), function (data) {
        $("#asd1").html(data);
    });
}

function getww3() {
    $.get("file.php?opt1=" + $("#id3"), function (data) {
        $("#asd1").html(data);
    });
} //and further
4
  • 1
    I'd say use a counter, and call the same function again Commented Nov 16, 2015 at 3:44
  • do you want the $.get to run in series or parallel? Commented Nov 16, 2015 at 3:45
  • @JaromandaX parallel... my only issue in the loop, the loop parameter name getww1, getww2...>>>getww10 Commented Nov 16, 2015 at 3:52
  • Why you want 10 different JS function for this. Instead of that go for single "funtion getww(number) " and pass required integer value like 1 to 10 while calling it. Commented Nov 16, 2015 at 3:58

2 Answers 2

1

Something like that :

function getResource(which) {
    $.get('file.php?opt1=' + $('#id' + which), function (data) {
         $('#asd' + which).html(data);
    }
}

for (var i = 0, max = 3; i < max; i += 1) {
    getResource(i);
}

But your code contains a few oddities.

  • $('#id1') is a jquery object, so it can't be sent to the server as a string.
  • If you always replace the $('#asd1').html(data) in each callback, it will get overwritten each time you get an answer from the server. That's why I made it dynamic also.
Sign up to request clarification or add additional context in comments.

Comments

0

If you need it to just run through a forloop, then start at 1 in order to accommodate your name and id.

for(var i = 1; i <= 10; ++i)
        $.get("file.php?opt1=" + $("#id" + i),    function (data) {
            $("#asd1").html(data);
    });

Now since get is asynchronous, each one will not wait for the other to complete.


If you need each function to be created, getww1 and such, then I recommend using eval to create those functions for you. But, that is very inefficient to do and should be avoided unless there is a specific requirement. Ex:

...
eval("(function () { return function "
     +fname+" (){"+
     codeAsString
     +"};})()"));
...

That will return the newly created function.

I hope this helps to some degree.

Comments

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.