0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.