Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate "Select" tag in HTML using JavaScript

<form action="#" class="group" method="post" onsubmit="return checkforblank()">
    <legend><span class="number">1</span>Departing & Arriving</legend>
    <fielset class="col-sm-6">
        <label for="FDestination">From</label>
        <select name="Location" id="Location">
            <option value="Please Select">Please Select</option>
            <option value="Newport">Newport</option>
            <option value="Mahdi">Mahdi</option>
            <option value="Cardiff">Cardiff</option>
            <option value="Cilo">Cilo is</option>
        </select>
    </fieldset>
</form>

<script>
    function checkforblank(){
        if (document.getElementsByID('Location').value== "Please Select") {
            alert('Please enter first name');
            document.getElementById('Location').style.borderColor = "red"; 
            return false; 
        }
    }
</script>

How can I display error when user chooses "Please Select" option from fieldset?

like image 560
el mashrafi Avatar asked May 02 '26 13:05

el mashrafi


1 Answers

How can I display error when user chooses "Please Select" option from fieldset?

You are already validating form submit, now you only need to add the same validation function for select onchange:

function checkforblank() {
    
    var location = document.getElementById('Location');
    var invalid = location.value == "Please Select";
 
    if (invalid) {
        alert('Please enter first name');
        location.className = 'error';
    }
    else {
        location.className = '';
    }
    
    return !invalid;
}
.error {border: 1px red solid;}
<form action="#" class="group" method="post" onsubmit="return checkforblank()">
    <legend><span class="number">1</span>Departing & Arriving</legend>
    <fielset class="col-sm-6">
        <label for="FDestination">From</label>
        <select name="Location" id="Location" onchange="checkforblank()">
            <option value="Please Select">Please Select</option>
            <option value="Newport">Newport</option>
            <option value="Mahdi">Mahdi</option>
            <option value="Cardiff">Cardiff</option>
            <option value="Cilo">Cilo is</option>
        </select>
    </fieldset>
    <button>Save</button>
</form>

You will not see alert in demo, as it's not allowed in snippet sandboxed iframe :(

like image 113
dfsq Avatar answered May 04 '26 01:05

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!