1

I think I have a simple question.

I'm trying to translate these 4 functions into a loop:

function Incr1(){
    document.forms[0].NavigationButton.value='Next';
    document.PledgeForm.FUDF9.value='Y1';
    document.forms[0].submit();}

function Incr2(){
    document.forms[0].NavigationButton.value='Next';
    document.PledgeForm.FUDF9.value='Y2';
    document.forms[0].submit();}

function Incr3(){
    document.forms[0].NavigationButton.value='Next';
    document.PledgeForm.FUDF9.value='Y3';
    document.forms[0].submit();}

function Incr4(){
    document.forms[0].NavigationButton.value='Next';
    document.PledgeForm.FUDF9.value='Y4';
    document.forms[0].submit();}

This is where I'm at with it, but it's not working.

for (var i = 1; i < 5; i++) {
    function 'Incr'+i(){
        document.forms[0].NavigationButton.value='Next';
        document.PledgeForm.FUDF9.value='Y'+i;
        document.forms[0].submit();
    }
}

Thank you for your help!!!

Katy O
  • 35
  • 7
  • why it isn't working? Do you get any error? One thing you can try first of all is to change the function name from 'Incr'+i to something like `IncrementFun()` – fbid Apr 11 '16 at 21:40
  • Please specifify what error message you get, instead of just telling us "it's not working". We can't help you if we have no indicators for what the problem is. – Frxstrem Apr 11 '16 at 21:41
  • You cannot use an expression for the name of a variable or function declaration. You'll want to use an array. – Bergi Apr 11 '16 at 21:43
  • It would make more sense to just use one function that you can pass your `incr` value into: `function incr(val){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y'+ val; document.forms[0].submit();}` – jmcgriz Apr 11 '16 at 22:05

1 Answers1

3

You could use an object:

var obj = {};

for (var i = 1; i < 5; i++) {
    (function(i) {
        obj['Incr' + i] = function() {
            //document.forms[0].NavigationButton.value = 'Next';
            //document.PledgeForm.FUDF9.value = 'Y' + i;
            //document.forms[0].submit();
            document.write(i + '<br>');
        }
    })(i);
}

obj.Incr3();
   
obj.Incr4();
isvforall
  • 8,768
  • 6
  • 35
  • 50