I had have a form with dropdowns and other fields that may be tagged as .related and if the dropdown value selected is 1 it displays the other fields. This works well but I want to add class "required" to their input classes. I tried the code below but it does not work.
<div class="related row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="OptionId">Pay by</label>
<select class="form-control input-lg" id="OptionId" name="OptionId" required="required">
<option value="">-- Choose --</option>
<option value="1">Transfer</option>
<option value="2">Cheque</option>
</select>
</div>
</div>
<div class="row">
<div class="requiredfields">
<div class="col-md-offset-05 col-md-3">
<div class="form-group">
<label class="control-label" for="AcctName">Account Name</label>
<input class="form-control input-lg" data-val-requiredif="Account Name Required" data-val-requiredif-expression=""OptionId==1"" id="AcctName" name="AcctName" type="text" value="" />
</div>
</div>
<div class=" col-md-offset-05 col-md-2">
<div class="form-group">
<label class="control-label" for="Bank">Bank Account</label>
<input class="form-control input-lg" data-val-requiredif="Account Number Required" data-val-requiredif-expression=""OptionId==1"" id="Bank" name="Bank" type="text" value="" />
</div>
</div>
</div>
</div>
</div>
I have this code below which was initially customised for only one field. But I now want to have something generic and reusable that will meet the requirements based on the markup I have explained above.
var showHideFieldsSelect = function (el, val) {
el.each(function () {
var select = $(this).find("select").first(),
dVersion = $('[name=Version]');
select.change(function () {
var thisOption = $(this);
if (thisOption.find(":selected").val() === val) {
thisOption.closest(".related").find(".requiredfields").show();
thisOption.closest(".related").find(".sub").hide();
} else {
thisOption.closest(".related").find(".requiredfields").hide();
}
thisOption.val() ? id.fadeIn() : id.hide();
console.log(thisOption.find(":selected").val())
thisOption.find(":selected").val() === "1" ? dVersion.addClass('required') : dVersion.removeClass('required');
}).trigger("change");
});
}
showHideFieldsSelect(related, '1');
I need help because my javascript library has become messed up. Preferably there is a default fluent validation which is failing to trigger but it puts the required markup with fields example below
"data-val-requiredif="Account Name Required" data-val-requiredif-expression=""OptionId==1""
It will be best if a proposed solution will pick these elements and add the required attribute to the input field.I have tried a lot of options to make this default validation work but to no avail. So now I have to do a hack.
That is to say
It checks the Id value of selected optionId say if is 1 and add the class "required" to all related fields that have markup "data-val-requiredif-expression=""OptionId==1""