Passing dynamic values to javascript function

Discussion in 'JavaScript' started by look4guna, Dec 30, 2010.

  1. #1
    Hi friends,

    i've javascript function called vote(id). this id can be used to make db changes. in html i have content like this:
    <div id="voteid0" onclick="vote(dbresult[0])" >some topic</div
    <div id="voteid1" onclick="vote(dbresult[1])" >some topic</div>
    <div id="voteid2" onclick="vote(dbresult[2])" >some topic</div>

    Here parameter for onclick function is loaded from db. after this i've a button which fetches new value from db using ajax request, that time i need to set this db value to onclick function. for example dbresult is an array which has the db contents and set() is the js functions and it has,
    var obj;
    for (i=0;i<dbresult.length;i++)
    {
    obj=document.getElementById("voteid"+i);
    obj.onclick=function() { dbresult; };
    }
    Now, the problem is only last value from the db result is set to onclick function of all div.

    can any one help me to get out of this problem??
     
    look4guna, Dec 30, 2010 IP
  2. look4guna

    look4guna Active Member

    Messages:
    60
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #2
    look at this below code:

    <html>
    <head>
    <script type="text/javascript">
    function val(value)
    {
    alert(value);
    }
    function change()
    {
    var arr= "3,4";
    arr=arr.split(",");
    for(i=1;i<=2;i++)
    { alert("df");
    var obj=document.getElementById("a"+i);
    //obj.onclick=null;
    obj.onclick=function() { arr[i-1]; }
    }
    }
    </script>
    </head>
    <body>
    <input type="button" id="btn1" onclick="change()" value="change"/>
    <div><a href="#" id="a1" onclick="val(1)">click</a></div>
    <div><a href="#" id="a2" onclick="val(2)">click</a></div>
    </body>
    </html>

    here after i click the change button the value for onclick should be changed as 3 and 4 for a1,a2 repectively. but its not working. help please?
     
    look4guna, Dec 31, 2010 IP
  3. look4guna

    look4guna Active Member

    Messages:
    60
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #3
    i made a mistake above, that line should be,
    var j=arr[i-1];
    obj.onclick=function() { val(j);
    but when i clicked both of alerted no: 4 only...
     
    look4guna, Dec 31, 2010 IP