Validate single Select form field
When the submit button is clicked, the value of the selected option is checked and if it is blank, a new paragraph element is inserted, the default form action is stopped, the select field is focussed and the submit button is disabled. Then when the select field is changed the submit input has the disabled attribute removed.
by paulyabsley
HTML
<form action="#" method="get" class="foo">
<select name="select" id="select">
<option value="">Select</option>
<option value="001">Option 1</option>
</select>
<input type="submit" />
</form>
<script>
$(document).ready(function() {
$('select').on('change', function () {
if ($(':submit').is(':disabled'))
{
$(':submit').prop('disabled',false);
}
$(".bar").remove();
});
$(":submit").click(function (event) {
if ($("#select option:selected").val()=='')
{
event.preventDefault();
$("#select").focus();
$(".foo").append('<p class="bar">Please Select an option!</p>');
$(":submit").prop("disabled", true);
}
});
});
</script>
JavaScript
/*$(document).ready(function() {
$('select').on('change', function () {
if ($(':submit').is(':disabled'))
{
$(':submit').prop('disabled',false);
$(".bar").remove();
}
});
$(":submit").click(function (event) {
if ($("#select option:selected").val()=='')
{
event.preventDefault();
$("#select").focus();
$(".foo").append('<p class="bar">Please Select an option!</p>');
$(":submit").prop("disabled", true);
}
});
});*/