-1

I am getting the data in json format as

{"a":null,"b":1001} 

and I have hidden field as

<input type="hidden" name="test" >

Now I need to set the value of field test as 1001 on page load. With jquery I am able to get the value in json but for some reason not getting as how do i set 1001 as value to hidden field.

Updated info.

Below is function I m using

$.get( "getjobscategoryid", {subcategory:data} )
    .done(function(json ) {   
        alert( "Data Loaded: " + json);
        $('input[name=subcategoryid]').val(json.jobscategoryid); 
        alert(json.jobscategoryid);
    });

data is the variable I m passing after capturing the text on page load.After I capture the text, I pass it to jquery get call and I can see that values are coming back perfectly.

and I get data as Data Loaded:[{"jobscategory":null,"jobscategoryid":1001}]

Not sure as why i get undefined message for alert.Let me check agian.

Kiran Badi
  • 501
  • 2
  • 9
  • 24

3 Answers3

3

Not sure as why i get undefined message for alert.

Because json is a string and strings don't have a jobscategoryid property. You have to parse the JSON into an object/array first.

$.get( "getjobscategoryid", {subcategory:data} ).done(function(json ) {
    var = $.parseJSON(json);
    $('input[name=subcategoryid]').val(data[0].jobscategoryid); 
});

See also Access / process (nested) objects, arrays or JSON


How do I know that json is a string you may ask? Because

alert( "Data Loaded: " + json);

gives you

Data Loaded:[{"jobscategory":null,"jobscategoryid":1001}]

If json was an object or array, you would get

Data Loaded: [object Object]

as output, because the default string representation of an object is [object Object].

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

JSFiddle

$(document).ready(function() {
    var jsonValue  = { "a": null, "b": 1001 };
    $('input[name=test]').val(jsonValue['b']);
});
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
0

this query very use full.

//returns {"exists":1} 0-open,1-already exist 
            var obj = jQuery.parseJSON( JSON.stringify(res) );

            if(obj.id){
            //$("#Language").html(obj.id);
            $('input[name=Language]').val(obj.id);
            }
Ram Kumar
  • 33
  • 9