Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  73] [ 1]  / answers: 1 / hits: 64031  / 12 Years ago, thu, november 8, 2012, 12:00:00

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'
};

More From » json

 Answers
38

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;
}


[#82112] Wednesday, November 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;