Renay
Renay

Reputation: 147

How to stop an event happening in Javascript

On this simple to-do list how do i stop the program from still creating a new paragraph when there is nothing in the text field. When Add To List is blank, i want the function to only output the alert, nothing else. I've tried many things but nothing has worked. Any help is greatly appreciated. Thanks!

JS Fiddle = http://jsfiddle.net/Renay/g79ssyqv/20/

<p id="addTask"> <b><u> To-Do List </u> </b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
   var input = document.getElementById('inputTask').value;
   var node=document.createElement("p");
   var textnode=document.createTextNode(input)
   node.appendChild(textnode);
   document.getElementById('addTask').appendChild(node);

   var removeTask = document.createElement('input');
   removeTask.setAttribute('type', 'button');
   removeTask.setAttribute("value", "Remove");
   removeTask.setAttribute("id", "removeButton");
   removeTask.addEventListener('click', function() {
      node.parentNode.removeChild(node);
   }, false)
   node.appendChild(removeTask);

   if (input == "") {
      alert('Please add an entry');
   }
}

Upvotes: 0

Views: 63

Answers (2)

Roberto Spagliccia
Roberto Spagliccia

Reputation: 1

You could just move the "creation" section in your else block

var input = document.getElementById('inputTask').value;

if (input == "") {
    alert('Please add an entry');

} else {

var node=document.createElement("p");
var textnode=document.createTextNode(input)
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);

var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener('click', function() {
    node.parentNode.removeChild(node);
}, false)
node.appendChild(removeTask);
}

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

Move your if statement to the top, just after your input variable is assigned to, and add a return to it to break out of the function:

function addText() {
    var input = ...;

    if (input == "") {
        alert("...");
        return;
    }

    var node ...;
    ...
}

Amended JSFiddle demo.

When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. (MDN)

Upvotes: 3

Related Questions