Return json from javascript function

I am trying to return a custom json object from a javascript function, my code is 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 a result like below

 { chk: [{val: 1}, {val: 2}], txt: 'test' }; 
+4
source share
2 answers

You need to define the chk variable in the json object. Since chk is undefined, it does not know that it is 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; }​ 
+4
source

chk is not defined as an array, which you need to first define as an array, and then pass the value to the 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; } 
+2
source

Source: https://habr.com/ru/post/1444732/


All Articles