i am tring to return custom json object from javascript function my code is as below
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'
};
asked Nov 8, 2012 at 5:59
Pragnesh Chauhan
8,49410 gold badges46 silver badges58 bronze badges
-
i have also refered this question' answer to add item stackoverflow.com/questions/4538269/…Pragnesh Chauhan– Pragnesh Chauhan2012年11月08日 06:03:40 +00:00Commented Nov 8, 2012 at 6:03
2 Answers 2
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;
}
answered Nov 8, 2012 at 6:06
Varun Achar
15.2k7 gold badges59 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Pragnesh Chauhan
it returns something like this
{chk: [ {0:[val : 1]}, {1:[val : 2]}] , txt: 'test'};Varun Achar
the 0 and 1 are the indices of the array. they are not part of the object inside the array. The output is exactly what you mentioned in your question. If you want to check, iterate the array and print out the values, you wont see the 0 and 1
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;
}
answered Nov 9, 2012 at 5:00
Gaurav Ramanan
3,7032 gold badges24 silver badges32 bronze badges
Comments
lang-js