0

I have this code in Ajax/Javascript where I am generating a dynamic table that should hold some returned value. At the beggining of each row I would like to have a column of radio buttons, that I could use to identify a particular row. How can I create radio buttons inside the table? Thanks

Here is my code:

for (var i = 0; i < controller_data.length; i++) {
    tr = $('<tr/>');


    // this is the row where the radio button should be

    tr.append("<td> <input type="radio"> </td>");
    tr.append("<td>" + controller_data[i].id + "</td>");
    tr.append("<td>" + controller_data[i].question + "</td>");
    tr.append("<td>" + controller_data[i].image + "</td>");
    tr.append("<td>" + controller_data[i].answer1 + "</td>");
    tr.append("<td>" + controller_data[i].answer2 + "</td>");
    tr.append("<td>" + controller_data[i].answer3 + "</td>");
    tr.append("<td>" + controller_data[i].answer4 + "</td>");
    $('table').append(tr);
}
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • OK. I have managed to create them by escaping the quotes, but they don't seem to work together as they are not inside a form. –  Dec 28 '15 at 01:50

2 Answers2

0

Doing only two rows, it would look like this...

     tr.append("<td><input name='question1'  type='radio' value='" + controller_data[i].answer1  + "'/>"+ controller_data[i].answer1  + "</td>");
     tr.append("<td><input name='question1'  type='radio' value='" + controller_data[i].answer2  + "'/>"+ controller_data[i].answer2  + "</td>");

it is the radio button name that groups raido buttons. Also, you go back and fourth between single and double quotes as I did, you do not have to do as much escaping. Also, I put in the answer in the value but if you have an answer id, that would actually be the value to put there.

Bindrid
  • 3,655
  • 2
  • 17
  • 18
  • Thanks. I just added the name='radiobutton' and now they work together. If I add an id that will hold the value of [i], would I be able to know which radio button I have selected? –  Dec 28 '15 at 02:03
  • Cause I am to lazy to type it out, take a look here http://stackoverflow.com/questions/9618504/get-radio-button-value-with-javascript – Bindrid Dec 28 '15 at 02:25
0

You can do it this way.

Just remove double quotes and replace it with single quotes, otherwise it will treat radio as a variable

for (var i = 0; i < controller_data.length; i++) {
tr = $('<tr/>');


// this is the row where the radio button should be
//CHANGE BELOW
tr.append("<td> <input type='radio'> </td>");
tr.append("<td>" + controller_data[i].id + "</td>");
tr.append("<td>" + controller_data[i].question + "</td>");
tr.append("<td>" + controller_data[i].image + "</td>");
tr.append("<td>" + controller_data[i].answer1 + "</td>");
tr.append("<td>" + controller_data[i].answer2 + "</td>");
tr.append("<td>" + controller_data[i].answer3 + "</td>");
tr.append("<td>" + controller_data[i].answer4 + "</td>");
$('table').append(tr);

}

Hemal
  • 3,682
  • 1
  • 23
  • 54