Home > DeveloperSection > Forums > How to call function with variable as paramenter in jquery?
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    March-18-2015 6:50 AM

 JavaScript JQuery  Jquery Selectors 
Ratings:


 1 Reply(s)
 637  View(s)
Rate this:

I want to call the function fill() with a variable as parameter. Everytime next() is called, the number of the variable should increase. So first, fill( q1 ) is called, then fill( q2 ) and so on. But apparently, you can't use variables as parameters. Any ideas?

var q1 = [2, "ff", "dd", "ss", "hh"];

    var q2 = [2, "ff", "dd", "ss", "hh"];

 

    var fill = function (data) {

        $("#number").html(data[1]);

        $("#cat").html(data[2]);

        $("#ques span").html(data[3]);

        $("#answ .answ:nth-child(1) button").html(data[4]);

        $("#answ .answ:nth-child(2) button").html(data[5]);

        $("#answ .answ:nth-child(3) button").html(data[6]);

        $("#answ .answ:nth-child(4) button").html(data[7]);

        $("#answ .answ:nth-child(" + data[0] + ") button").attr("data-state", "correct");

    }

    var count = 1;

    function next() {

        fill("q" + count);

        count++;

    }



Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    March-18-2015 7:48 AM

I would think a better approach is to make a multi-dimensional array q, in stead of q1 and q2 etc.

var q = [];

    q[0] = [2, "ff", "dd", "ss", "hh"];

    q[1] = [2, "ff", "dd", "ss", "hh"];

 

    var fill = function (data) {

        $("#number").html(data[1]);

        $("#cat").html(data[2]);

        $("#ques span").html(data[3]);

        $("#answ .answ:nth-child(1) button").html(data[4]);

        $("#answ .answ:nth-child(2) button").html(data[5]);

        $("#answ .answ:nth-child(3) button").html(data[6]);

        $("#answ .answ:nth-child(4) button").html(data[7]);

        $("#answ .answ:nth-child(" + data[0] + ") button").attr("data-state", "correct");

    }

    var count = 0;

    function next() {

        fill(q[count]);

        count++;

    }

This way, you could also check that you're not passing undefined to fill():

function next() {

        if (count < q.length) {

            fill(q[count]);

            count++;

        }

    }


Don't want to miss updates? Please click the below button!

Follow MindStick