HOW TO CALL FUNCTION WITH VARIABLE AS PARAMENTER IN JQUERY?

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
 1081  View(s)
Ratings:
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++;

    }

  1. Royce Roy

    Post:149

    Points:1043
    Re: How to call function with variable as paramenter in jquery?

    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++;

            }

        }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!