I have two radio buttons, Yes and No. When Yes is clicked I display some content and hide it when No is clicked. The content is initially hidden, it is displayed only when Yes is clicked. They work just as intended, but the problem is that after I submit the form my content gets hidden even when the radio button Yes is clicked, I need a way to let it stay displayed after form submission if the user clicked Yes
Here are my radio buttons:
@Html.RadioButtonFor(n => n.HasCompanyVehicle, "Yes", new { @class = "form-check-input ", @id="hasVehicle", onclick="showCompanyPolicyAndLicence();" })
@Html.RadioButtonFor(n => n.HasCompanyVehicle, "No", new { @class = "form-check-input ", @id="noVehicle", onclick="showCompanyPolicyAndLicence();" })
And my function:
let showCompanyPolicyAndLicence = () => {
let policyVehicleElem = document.querySelector("#policyVehicleElem");
let buttonYes = document.querySelector("#hasVehicle").checked;
let buttonNo = document.querySelector("#noVehicle").checked
if (buttonYes == true) {
policyVehicleElem.classList.remove("hide");
} else if (buttonNo == true) {
policyVehicleElem.classList.add("hide");
}
};
The content to be hidden/displayed:
<span class="hide" id="policyVehicleElem">
<span>
@Html.LabelFor(m => m.VehiclePolicy, new { @class="form-label" })
</span>
@Html.TextBoxFor(m => m.VehiclePolicy, new { @type = "file", @class="form-control form-control-sm" })
@Html.ValidationMessageFor(m => m.VehiclePolicy, "", new { @class = "text-danger" })
<br />
<span>
@Html.LabelFor(m => m.LicenceExpiryDate, new { @class="form-label" })
</span>
<br />
@Html.TextBoxFor(m => m.LicenceExpiryDate, new { @type = "date", @class="form-control form-control-sm" })
@Html.ValidationMessageFor(m => m.LicenceExpiryDate, "", new { @class = "text-danger" })
</span>
Based on my little knowledge of javascript, I suggest you try the following:
$(document).ready(function(){
var hasVehicle = document.getElementById(‘hasVehicle’);
var noVehicle = document.getElementById(‘noVehicle’);
if(hasVehicle.checked){
“Display your div”
}
if(noVehicle.checked){
“Hide your div”
}
// when the user submit the form you should redirect the page to the same url.
// your script goes here.
}
I hope this can fix your problem.