javascript - Add li to ul with looking for if exists -
i'm adding thinks getting input field list. adding function works want check if string, user wants add exists. want don't know right functions use
html
first name: <input type="text" id="firstname"> <br> <p>other people's names:</p> <ul id="demo"></ul> <input type='button' onclick='changetext2()' value='submit' />
javascript
var list = document.getelementbyid('demo'); function changetext2() { var firstname = document.getelementbyid('firstname').value; var listelement = list.getelementsbytagname("li"); // here missing code if (listelement.text not in list){ var entry = document.createelement('li'); entry.appendchild(document.createtextnode(firstname)); list.appendchild(entry); } else alert("is in !"); }
edit*
the code above in jsfiddle.
you create array , push in each name, add first time. each time try insert new item, check in array see if name has been added. in terms of code:
var addednames = []; var list = document.getelementbyid('demo'); function changetext2() { var firstname = document.getelementbyid('firstname').value; // array object has method called indexof, 1 argument // item looking for. if item not in array, // method returns -1. otherwise, method returns it's position. // instance, let have defined following array. // var numbers = [1,2,3,4]. // numbers.indexof(5) returns -1. // while numbers.indexof(4) returns 3. if (addednames.indexof(firstname)==-1){ var entry = document.createelement('li'); entry.appendchild(document.createtextnode(firstname)); list.appendchild(entry); // add inserted name in array later checks. addednames.push(firstname); } else alert("is in !"); }
please have jsfiddle
Comments
Post a Comment