I'm trying to get an error message when select is set to default and nothing is selected. For input fields the code works, but I can't figure out where I'm wrong for the select part. Anyone help me?
Fiddle: https://jsfiddle.net/snake93/1sLtk2a7/2/
//Error Msg for input field
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<input type="text" name="fname" form="myForm">
<select id="select-sex" form="myForm" name="radios">
<option id="opt-default" form="myForm" selected>Select...</option>
<option id="sexuomo" name="radios" value="Male" form="myForm">Uomo</option>
<option id="sexdonna" name="radios" value="Female" form="myForm">Donna</option>
</select>
<button onclick="validateForm()">Submit</button>
<form name="myForm" id="myForm" onsubmit="return validateForm()" method="post">
</form>
CodePudding user response:
Just repeat your logic you used on the input
for the select
:
However, a much more scalable solution is to add the required
field to your inputs, then use checkValidity()
:
function validateForm(){
const isValid = myForm.checkValidity();
if(!isValid){
alert("Please fill all fields");
}
return isValid;
}
<form name="myForm" id="myForm" onsubmit="return validateForm()" method="post" novalidate>
<input type="text" name="fname" form="myForm" required>
<select id="select-sex" form="myForm" name="radios" required>
<option id="opt-default" value="" form="myForm" selected disabled>Select...</option>
<option id="sexuomo" name="radios" value="Male" form="myForm">Uomo</option>
<option id="sexdonna" name="radios" value="Female" form="myForm">Donna</option>
</select>
<button>Submit</button>
</form>
CodePudding user response:
An <option>
without a value=
defaults to the text value of that option. ie
<option>Seleziona</option>
is the same as
<option value="Seleziona">Seleziona</option>
So you either need to check for "Seleziona" or you need to give it a value.
<option value="">Seleziona</option>
Note: Seleziona comes from OPs fiddle
Updated snippet:
//Error Msg for input field
function validateForm() {
let name = document.forms["myForm"]["fname"].value;
let gender = document.forms["myForm"]["radios"].value;
if (name == "" || gender == "") {
alert("Name and gender must be filled out");
return false;
}
}
<input type="text" name="fname" form="myForm">
<select id="select-sex" form="myForm" name="radios">
<option id="opt-default" form="myForm" value="" selected>Seleziona</option>
<option id="sexuomo" name="radios" value="Male" form="myForm">Uomo</option>
<option id="sexdonna" name="radios" value="Female" form="myForm">Donna</option>
</select>
<button onclick="validateForm()">Submit</button>
<form name="myForm" id="myForm" onsubmit="return validateForm()" method="post">
</form>