How to get the radio status dynamically created?

Alick Wang 226 Reputation points
2023-12-02T02:35:25.1833333+00:00

Radio groups are created dynamically,like:

function add(){

str= "<td><input name='rd' value='aa' type='radio'></td>"

+ "<td><input name='rd' value='bb' type='radio'></td>"

$("#tr1").append(str);

}

//This function may be called manny times.

Then how can I get the radio status like this ,

  $("#tr1").each(function (index, item) {...}

First ,the radio groups are wrong if there are more than 2 rows,

second ,If the raido name is not fixed ,how can i get the radio status.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,009 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 1,500 Reputation points
    2023-12-02T11:57:22.63+00:00

    Radio buttons allow a user to make a selection from several options. The radio button name attribute groups the radio buttons. When a radio button from a group is selected then the others radio button are deselected. In your use case the name attributes must be different for each record. It up to you to design the code. I would use an index which is the same concept the model binder to populate an array of records.

    Reference documentation

    <input type="radio">

    Basic example.

    
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    <div>
        <table>
            <tr>
                <td>
                    <input name='[0]rd' value='aa' type='radio'>
                    <input name='[0]rd' value='bb' type='radio'>
                </td>
                <td><button type="button" class="MyButton">Get Radio Value</button></td>
            </tr>
            <tr>
                <td>
                    <input name='[1]rd' value='cc' type='radio'>
                    <input name='[1]rd' value='dd' type='radio'>
                </td>
                <td><button type="button" class="MyButton">Get Radio Value</button></td>
            </tr>
        </table>
    </div>
    <div>
        
    </div>
    <div id="result">
    </div>
    
    @section scripts {
        <script>
            $('.MyButton').click(function () {
                var row = $(this).closest("tr");           
                var rd = $(row).find('input[type="radio"]:checked').val();
                console.log(rd);
            });
        </script>
    }
    
    0 comments No comments