Search code examples
javascripthtmlformscomputer-scienceweb-development-server

I want to return 'Alert' box if someone submits empty form


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, 
    initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>To Do List</h1>
    <form>
        <input autocomplete="off" autofocus id="todotext" 
        type="text">
        <input onclick="serve(); return false" type="submit">
    </form>

    <ol id="add"></ol>

</body>

<script>
    function serve(){
        const neww = document.getElementById('add');
        let text = document.getElementById('todotext').value;
        const a = document.createElement('li');
        a.innerText = text;
        neww.appendChild(a);
        document.getElementById('todotext').value = "";
    }
</script>
</html>

Here is my code and I want to return an 'Alert' if someone submit empty form. How should I do it ? Any help will be appreciated

Here's an image:

This is the Image, Click here


Solution

  •  String.prototype.isEmpty = function() {
        return (this.length === 0 || !this.trim());
    };
     
     function serve(){
            const neww = document.getElementById('add')
            let text = document.getElementById('todotext').value;
            if( text.isEmpty() ){
                alert('cannot be blank');
              return;
            }
            const a = document.createElement('li')
            a.innerText = text
            neww.appendChild(a)
            document.getElementById('todotext').value = ""
        }
    <h1>To Do List</h1>
        <form>
            <input autocomplete="off" autofocus id="todotext" 
            type="text">
            <input onclick="serve(); return false" type="submit">
        </form>
        <ol id="add"></ol>