Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Json object, get by value by Key String.. Ex : GetMyVal(MyKeyInString)

I have this json info:

data.ContactName
data.ContactEmal
data.Departement

I Would like to have a function like that

function GetMyVal(myStringKey)
{
   $.Ajax
         ,... 
         , ...
         ,success :function(data)
    {
       $("#mytarget").val(data.myStringKey);
    }

}

Call Like that GetMyVal("ContactName");

like image 471
Jean-Francois Avatar asked Dec 22 '22 16:12

Jean-Francois


1 Answers

Solution:

Try changing:

$("#mytarget").val(data.myStringKey);

to:

$("#mytarget").val(data[myStringKey]);

Explanation:

Here is what those constructs mean:

    $("#mytarget").val(SOMETHING);
change the value of the element with id "mytarget" to SOMETHING

    data.myStringKey
take the object named "data" and give me the value of its property named literally "myStringKey"

    data[myStringKey]
take the object named "data" and give me the value of its property named like a value of the variable named "myStringKey"

like image 68
rsp Avatar answered Jan 17 '23 15:01

rsp