justiceorjustus justiceorjustus - 2 months ago 5
jQuery Question

JQuery function - run on click and on page load for specific radio button

New to JQuery and I have the following function. I am trying to modify it so it does 2 things: Not trigger the function when I click other radio buttons (I thought '#UpdateType input[type="radio"]' would do this) and also run the function on load as well as on click. #UpdateType is the ID for the radio buttons I'm using this with. Does anyone have any suggestions?

$(document).ready(updateTypeFunc);
$(document).ready(function () {
$('#UpdateTypeRB input[type="radio"]').click(updateTypeFunc);
});
function updateTypeFunc()
{
if ($(this).attr('id') == 'UpdateType' && $(this).val() == 'Current') {
$('.current-employee').show();
}
else {
$('.current-employee').hide();
}
}


As of right now it fires when I click any radio button regardless of the ID.

Edit: HTML

<div class="col-md-10" id="UpdateTypeRB">
<label class="radio-inline">
<input class="btn btn-primary" 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 checked="checked" class="btn btn-secondary" 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>


Razor:

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


Edit 2: Updated JQuery thanks to @KristianBarrett. Works other than the $(document).ready I tried to implement.

What I'm overall trying to achieve is hiding / showing certain required elements on the page based on this radio button tick. It initially loads with none checked so the user is forced to pick one. I then use Foolproof to do RequiredIf's based on those check boxes (the 'Current' tick) and want to show them to the user after 'Current' is ticked with JQuery. The problem is when validation throws an ErrorMessage after the Submit, the Current checkbox is ticked still however the fields are hidden until I manually click it again. The fields are hidden by default.

Answer

You need to make two different options:

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

Then you can apply @checked = true to your radio button you want to have clicked at page load. Like this

@Html.ValidationMessageFor(m => m.UpdateType, "", new { @class = "text-danger", @checked = true })

When you bind your values to two different values on your model, then your server will parse the selected one, and should set them correctly once it returns your view.

After that you need to apply the answer stweb gave you, but you need to look for the checked one.

So you should do something like:

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

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

you need to reapply the javascript everytime the page runs. So you iterate your check boxes and finds the checked one and clicks it.

$('input[type=radio]:checked')

this will give you the checked radio button. Then you can pass it to the clickFunc on $(document).ready()

EDIT:

Another thing you are doing is hardcoding against some specific IDs. You should rather think more generally. Like selecting all the radio buttons and then finding the checked one. This makes your code less error prone, when you change your ID of the model. The more generally you can make the code, the less you have to maintain.