html - Addding a item to a list in JavaScript -
i'm debutant in javascript please patient me, in code have list of ingredients, when user puts in input area , click on body, text must added item in list before last one, code not working , can't find problem.
<!doctype html> <html> <head> <title>kitchen</title> <script type="text/javascript"> function ajout(){ var newingredient = document.createelement("li"); var ingredient = document.getelementbyid("in2").value; var text=document.createtextnode(ingredient); newingredient.appendchild(text); var lastone=document.getelementbyid("last"); var list=getelementbyid("listecommissions"); list.insertbefore(newingredient, lastone); } </script> </head> <body onclick="ajout()"> <br /><br /><br /> <ul id="listecommissions"> <li> 1kg de farine </li> <li> un pack de lait </li> <li id="last"> add 1 more ... </li> </ul> <form> <input type=text id="in2" placeholder="add ingredient"/> </form> </body> </html>
so, main problem line
var list = getelementbyid("listecommissions");
which should be
var list = document.getelementbyid("listecommissions");
this discovered when use debugger tools (web console). second thing onclick
should onclick
. see jsfiddle here.
i recommend separate javascript html i. e. use no inline tags js. can adding domcontentloaded
eventlistener window
, within add eventlistener body
(in case) or better button:
window.addeventlistener('domcontentloaded',function(){ document.getelementbyid('yourbuttonidhere') .addeventlistener('click',function(){ var newingredient = document.createelement("li"); var ingredient = document.getelementbyid("in2").value; var text = document.createtextnode(ingredient); newingredient.appendchild(text); var lastone = document.getelementbyid("last"); var list = document.getelementbyid("listecommissions"); list.insertbefore(newingredient, lastone); }); });
Comments
Post a Comment