Razor- Giving an 'attribute' to a radioButtonFor

Viewed 24

I have radio buttons that are defined like this

 @foreach (var actionType in partActionTypes)
 {
    <td>
         @Html.RadioButtonFor(x => x.Parts[i].SelectedActionType, actionType, new { name = "partRadio" })
    </td>
 }

Where I try setting the 'name as "partRadio", (I tried doing @name and Name but neither option worked.

In my JQuery code I have it where a row is cloned after a checkbox is clicked, that code looks like this

 $(document).ready(function () {
            $('.tr_clone input.part-class').change(function () {

                let Id = $(this).attr('id');
                let partId = $(this).attr('data-partId');

                if ($(Id).is(":checked")) {
                    // remove cloned row

                    $("#AllTxt").hide();
                    $("#editQty").show();
                }
                else {
                    var $tr = $(this).closest('.tr_clone');
                    var $clone = $tr.clone();
                    $clone.find('td');
                    $tr.after($clone);
                    $($clone).find(".part-class").hide();
                    $clone.find('input[type="radio"]').attr("name", function (el) { return el.name + 'clone' });
                    $("#AllTxt").show();
                    $("#editQty").hide();               
                }

            });
        });

Where it should just be appending 'clone' to 'partRadio' but instead the HTML is rendering the name as 'name = undefinedclone`

Why is this?

1 Answers

The problem is because the first argument of the attr() handler function is the index of the element, not a reference to the element itself.

To fix this you need to accept the element correctly using the second argument provided to the function which is the current value of the name attribute:

$clone.find('input[type="radio"]').attr("name", function (i, n) { 
   return n + 'clone' 
});

Note that this can be shortened using an arrow function:

$clone.find('input[type="radio"]').attr("name", (i, n) => n + 'clone');
Related