justiceorjustus justiceorjustus - 2 months ago 12
jQuery Question

JQuery on radio button click Uncaught throwing TypeError: Cannot read property 'indexOf' of undefined

I have a form which when you click / check a specific radio button, it shows or hides some elements. This function also needs to run on page load in case MVC validation comes back with an error on post. The problem is I'm getting

TypeError: Cannot read property 'indexOf' of undefined
on page load, and although the code does work, it breaks all of the code below it in the scripts section. I'm coming to the conclusion that I am not checking which radio button is selected properly here:
if ($element.attr('class').indexOf('update-type-check-current') !== -1)
.

JQuery:

$(document).ready(function () {
$('#CurrentEmployeeRB input[type="radio"]').click(function () {
clickFunc($(this));
});
clickFunc($('#CurrentEmployeeRB input[type=radio]:checked'));
});

function clickFunc($element) {
var currentEmployee = $('.current-employee');
if ($element.attr('class').indexOf('update-type-check-current') !== -1) {
currentEmployee.show();
}
else {
currentEmployee.hide();
}
}


HTML:

<div class="form-group">
<label class="col-md-2 control-label" for="UpdateType">New or Current?</label>
<div class="col-md-10" id="CurrentEmployeeRB">
<label class="radio-inline">
<input class="btn btn-primary update-type-check-new" data-val="true" data-val-required="Please select whether the employee is new or current." id="UpdateType" name="UpdateType" type="radio" value="New"> New
</label>
<br>
<label class="radio-inline">
<input class="btn btn-secondary update-type-check-current" id="UpdateType" name="UpdateType" type="radio" value="Current"> Current
</label>
<br>
<span class="field-validation-valid text-danger" data-valmsg-for="UpdateType" data-valmsg-replace="true"></span>
</div>
</div>


Razor:

<div class="form-group">
@Html.LabelFor(m => m.UpdateType, new { @class = "col-md-2 control-label" })
<div class="col-md-10" id="CurrentEmployeeRB">
<label class="radio-inline">
@Html.RadioButtonFor(m => m.UpdateType, "New", new { @class = "btn btn-primary update-type-check-new" }) New
</label>
<br />
<label class="radio-inline">
@Html.RadioButtonFor(m => m.UpdateType, "Current", new { @class = "btn btn-secondary update-type-check-current" }) Current
</label>
<br />
@Html.ValidationMessageFor(m => m.UpdateType, "", new { @class = "text-danger" })
</div>
</div>


Is there a different way I should be doing this? I'm just getting into learning JQuery and I'm not finding any working alternatives so far through searching.

Answer

You should change the line at ready

clickFunc($('#CurrentEmployeeRB input[type=radio]:checked'));

with

if($('#CurrentEmployeeRB input[type=radio]:checked').length >= 1) {
   clickFunc($('#CurrentEmployeeRB input[type=radio]:checked'));
}