0

I have dynamic radio buttons in VBTML page and jQuery. I have 3 radio buttons and when i am selecting first/second radio button and click on save. The selected Radio button text is correctly saving into database. But in frontend it is not selecting the saved Radio button text. Always it is selecting last Radio button. Please see my code in below. Please help me how to keep checked the selected radio button option.

<table>
<tr>
 <td>
@Code
    For Each item In Model.StudentCourseLookup
    Dim itemName = item.Text
    @<input type="radio" name="CourseDetails" id="@itemName" class="cbxStudentCourse" />
           @<span>@item.Text</span>
            @<br />
            Next
End Code
              @Html.TextBoxFor(Function(m) m.StudentCourse, New With {.style = "display: none;"})
                    </td>
</tr>
</table>

    <script type="text/javascript">

 if ($("#StudentCourse").val !== '') {
            
            var data1 = $("#StudentCourse").val();
            $.each(data1.split('|'), function (_, val) {
                if (val.length > 1) {
              
                    $(':input[name="CourseDetails"]').prop('checked', true);
                }
            });
        }



function OStudentCourseSave() {

 var studentCourseList = ''
            $('.cbxStudentCourse').each(function (index, cbx) {
                if (this.checked === true) {
                    studentCourseList = cbx.id;
                }
            });


 $("#StudentCourse").val(studentCourseList);

 var sc= @Html.Raw(Json.Encode(Model)); //Getting model 

sc.StudentCourse = $("#StudentCourse").val();

}
</Script>
kamal
  • 25
  • 7
  • 1
    you'd be much better off using a form, it'll save you from writing all those loops that just make the code unnecessarily complicated. Otherwise you are faced with the problem of reloading the page made by .Net technology. and for that you have to initialize the previously chosen radio element (which would also be done more easily if you used a form) – Mister Jojo Sep 02 '21 at 13:52
  • Set the `checked` property at the time your create the radio ` – freedomn-m Sep 02 '21 at 14:10
  • Or use `@Html.RadioButtonFor` and let the system re-populate it for you (see also https://stackoverflow.com/a/10805741/2181514) – freedomn-m Sep 02 '21 at 14:11

1 Answers1

0

The following piece of code is the problem:

if (val.length > 1) {
    $(':input[name="CourseDetails"]').prop('checked', true);
}

Since all the radio buttons have the same name you need to make it a bit more explicit and start using id's since this is what you're gathering anyway.

Try updating it to something like this to see if it helps:

$(':input[id="' + val + '"]').prop('checked', true);

Or even:

$('#' + val).prop('checked', true);
cycaHuH
  • 3,240
  • 1
  • 14
  • 11