Reputation: 95
I am attempting to set the age drop down as a required field. Also setting an empty "--" value, so that a value must be selected. Currently, people just leave it as "18" because it is already there.
Here is an example of having a required field:
<div class="row form-group">
<div class="col-md-12">
<input type="text" id="guestUsername" class="form-control fadeIn second" name="username" placeholder="Enter username" required>
</div>
</div>
This is the field I need to modify and unsure how to:
<div class="row form-group fadeIn second">
<div class="col-md-4">
<select class="form-control" name="age" id="age">
<?php for($age=18;$age<99;$age++):?>
<option value="<?=$age?>"><?=$age?> years</option>
<?php endfor;?>
</select>
</div>
Upvotes: 2
Views: 227
Reputation: 124
Try to check it before submitting form. If the user selects first option show the alert message, if not submit the form.
<form method="POST" id="myForm">
<select class="form-control" name="age" id="age" required>
<option>AGE</option>
<option value="18">18 Years</option>
</select>
</form>
<button onclick="Validate()">Submit</button>
<script>
function Validate(){
var a = document.getElementById('age').selectedIndex;
var b = document.getElementById('myForm');
if(a=="0"){
alert("Please Choose A Valid Option");
}else{
b.submit();
}
}
</script>
Upvotes: 0
Reputation: 219864
Add an empty <option>
before outputting the rest of the dropdown values. Then if it is empty when the form is submitted you can throw an error.
<select class="form-control" name="age" id="age" required>
<option></option>
<?php for($age=18;$age<99;$age++):?>
<option value="<?=$age?>"><?=$age?> years</option>
<?php endfor;?>
</select>
Sample
<form>
<select class="form-control" name="age" id="age" required>
<option>AGE</option>
<option value="18">18 years</option>
</select>
<input type="submit">
</form>
Upvotes: 1