Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

return json from javascript function issue

i am tring to return custom json object from javascript function my code is as below

Fiddle

html

<input type='checkbox' name='chk[]' value='1'>1
<input type='checkbox' name='chk[]' value='2'>2
<input type='text' id='txt' value='' />
<input id='btn' type='button' value='click' />​

js

var json = {};

$('#btn').click(function(){
  console.log(getdata());
});
function getdata(){
  $('input:checked').each(function(i){
      json.chk = $(this).val();
      //json.chk.push({"val": $(this).val()}); gives error Uncaught TypeError: Cannot call method 'push' of undefined
  });

  json.txt = document.getElementById("txt").value;

 return json;
}

​ i need result like below

{
  chk: [{val: 1}, {val: 2}],
  txt: 'test'
};

Upvotes: 5

Views: 68401

Answers (2)

Gaurav Ramanan
Gaurav Ramanan

Reputation: 3633

chk is not define as array you need to first define as an array then push value into array.

var json = {};

    $('#btn').click(function(){
      console.log(getdata());
    });
    function getdata(){
      $('input:checked').each(function(i){
         if(json.chk)
        {
            json.chk.push({val:$(this).val()})
        }
        else
        {
            json.chk=[];
            json.chk.push({val:$(this).val()})
        }
      });

      json.txt = document.getElementById("txt").value;

     return json;
    }

Upvotes: 2

Varun Achar
Varun Achar

Reputation: 15109

You need to define the chk varible in the json object. Since chk is undefined, it doesn't know that it's an array.

var json = {};

$('#btn').click(function(){
    console.log(getdata());
});
function getdata(){

    json.chk = [];
    $('input:checked').each(function(i){
        json.chk.push({ val : $(this).val()});
    });

    json.txt = document.getElementById("txt").value;

    return json;
}
​

Upvotes: 6

Related Questions