Here i have select option using select2, it works fine, but here i want select2 required with oninvalid custom text and when i select and save with button form, but it keeps displaying invalid text on button and can't save
This works if we directly select select2 and fill in the input and directly save
But it doesn't work when I press the button in the beginning and select the last one select2, it will keep displaying the text and that's the problem is there any way to fix it
$(".select").select2({
placeholder: "Pilih . . .",
allowClear: false,
});
.w-100{
width: 50%;
}
.btn{
width: 100px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet">
<h4>FORM 1</h4>
<form action="ins.php" method="POST" >
<select class="select w-100" oninvalid="this.setCustomValidity('Tidak Boleh Kosong')" oninput="this.setCustomValidity('')" required="" >
<option value=""></option>
<option value="1">Opsi 1</option>
<option value="2">Opsi 2</option>
<option value="3">Opsi 3</option>
<option value="4">Opsi 4</option>
<option value="5">Opsi 5</option>
</select>
<br><br>
<input type="text" class="w-100" oninvalid="this.setCustomValidity('Tidak Boleh Kosong')" oninput="this.setCustomValidity('')" value="" required="" />
<br><br>
<button class="btn btn-success">Simpan</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
The oninput event is only valid for input / textarea elements. For select elements onchange should be used instead. The onchange event occurs when the element looses focus and has a changed value.
Updating the select to use onchange as follows will correctly trigger the event.
<select class="select w-100" oninvalid="this.setCustomValidity('Tidak Boleh Kosong')" onchange="this.setCustomValidity('')" required="" >