super11 super11 - 6 months ago 7
Javascript Question

How to get find if the input is empty?

In my script everything works well except for the output for an empty input.

<input id="id1" type="number" max="100" min="40">

<button onclick="count()">OK</button>

<p id="test"></p>

<script>

var inpObj = document.getElementById('id1');

function count() {
if(inpObj.checkValidity() == false || inpObj.length === 0) {
document.getElementById('test').innerHTML = inpObj.validationMessage;
} else {
document.getElementById('test').innerHTML = "Input OK";
}
}

</script>


I have no idea why is this not working.

Thanks.

Answer

Try this :

function count() {
        if(inpObj.checkValidity() == false ) {
            document.getElementById('test').innerHTML = inpObj.validationMessage;
        } else if(inpObj.value.length === 0) {
            document.getElementById('test').innerHTML = "Empty"
        } else {
            document.getElementById('test').innerHTML = "Input OK";
        }
    }

See : https://jsfiddle.net/Ldj170Lc/

Comments