Scoped Validated Task List

Add text to a UL with some validation.

by davestein

HTML

<form id="task-creator">
    <input type="text" id="task-name" name="task-name" autocomplete="off" />
    <input type="submit" value="Add Task" />
    <div id="error-msg">Please enter valid task</div>
</form>

<h3>Task List</h3>
<ul id="tasks">
    
</ul>

CSS

h3 { margin: 20px 0; border-bottom: solid 1px #000; padding-bottom: 10px; }

#error-msg { color: #FF0000; display: none; margin-top: 10px; }

JavaScript

var MyApp = {
    
    
    initialize : function() {
        
      var form = document.getElementById('task-creator');
    
    
        form.onsubmit = function() {
            
            var task_name = document.getElementById('task-name').value,
                error     = document.getElementById('error-msg'),
                Item      = false;
            
            error.style.display = 'none';
                                                    
            // using match against a pattern, a whole class can be taught
            // on patterns so I can recommend tutorials later
            if ( !task_name.match(/^[A-Za-z0-9 ]+$/) ) {
                error.style.display = 'block';
                return false;
            }
            
            
            // create new Task
            Item = new MyApp.Task();
            
            // add task to list
            Item.add( task_name );
            
            // reset form
            form.reset();
            
            // prevent form from doing ugly submit
            return false;
            
        }; // onsubmit
        
    } // initialize
    
}; // MyApp

MyApp.Task = function() {

  this.list = document.getElementById( 'tasks' );

}; // Task 

MyApp.Task.prototype = {
    
    add : function( name ) {
        
        var list_item = document.createElement( 'li' );
        
        this.list.appendChild( list_item );
        
        list_item.innerHTML = name;
        
    }
    
}; // Task.prototype
    
    
MyApp.initialize();