views:

34

answers:

2

I have a group of radio buttons in a form, I need to pass the values of the selected radion buttons to a php script. So I need to build a json object to post.

I tried with this code, but I'm not sure. Please could anyone help me.

result = [];
for (i=0; i<document.getElementsByTagName('input').length; i++) {
    if (document.getElementsByTagName('input').item(i).checked) {
        s = document.getElementsByTagName('input').item(i).name;
        r = document.getElementsByTagName('input').item(i).value;
        result.push({id:s, va:r});
}
+1  A: 

If the name values are unique, just build a string like so:

var result = '', inputs = document.getElementsByTagName('input');

for ( var i = inputs.length; i--; ) {
    if ( inputs[i].checked ) {
        result+= ( inputs[i].name + '=' + inputs[i].value + '&' );
    }
}

Live demo: http://jsfiddle.net/TTvkb/

Then just send the string in your ajax request.

meder
A: 

Using jquery, the following is another way to do it:

var postData = {}, inputs = document.getElementsByTagName('input');

for ( var i = inputs.length; i--; ) {
    if ( inputs[i].checked ) {
        postData[inputs[i].name] = inputs[i].value;
    }
}

$.post('/post.php', postData, function(retData){
  // handle response
}); 
letronje