简体   繁体   中英

Create radio button inside dynamic generated table

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

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM