I have a scenario I will try to explain, sorry for my English.
I have created a form to submit some values , within the form user can select an option, but one option of which it is "Others specify..." when it is selected the hidden textarea is displayed and user can fill in some data. For the case that it is selected and user does not fill any data, the form is returned back due to validation failure but the textarea is no longer visible because onchange="selectOption();" is not triggered. Everything works fine but in my case I am trying to make the textarea visible with validation error message when it is returned back. How do I perfom this.
<form method="POST" action="{{route('employer-section-b.store')}}"> @csrf <div class="col-md-12">
<select name="b3" id="sector" class="form-control @error('b3') is-invalid @enderror" onchange="selectOption();">
<option value="" disabled selected>select</option>
<option value="1" @if (old('b3')=="1" ) {{ 'selected' }} @endif>Agriculture, forestry, and fishing </option>
<option value="2" @if (old('b3')=="2" ) {{ 'selected' }} @endif>Mining and quarrying</option>
<option value="14" @if (old('b3')=="3" ) {{ 'selected' }} @endif>Others specify……</option></select>
<div class="col-md-12 mt-2" id="specify" style="display: none">
<div class="form-floating mb-3">
<textarea rows="2" name="b3" class="form-control @error('b3') is-invalid @enderror" placeholder="Type here..">
{{ old('b3') }}</textarea>
</div></div>
</div>
</form>
Script to diplay textarea if others is selected
<script>
function selectOption() {
var sector = document.getElementById("sector").value;
var y = document.querySelector("#specify");
if (sector == 3) {
y.removeAttribute("style")
} else if (sector != 3) {
y.setAttribute("style", "display:none");
}
}
</script>
setAttribtueis the completely wrong way to add a style. Just useelement.style.display = 'none';. However, smart and modern developers will add/remove/toggle CSS classes withclassList. By taking the right approach your whole issues and the connected questions would resolve or change.</select>-tag. The approach is simple:if (sector == 3) { y.classList.remove('d-none); } else { y.classList.add('d-none); }Then simply disable the submit button if the textarea is empty or not.Other Specifyas selected but the textarea is invisible . How do I make the textarea also visible when validation error is returned. Thanks again.