Attempting my first Javascript project, playing around with DOM to make a To-Do List.
After adding an item, how do i get the 'Remove' button to function and remove the item + the remove button.
Furthermore, after a new entry is made, the list item still stays in the input field after being added. How can it be made to be blank after each list item.
And yes i know my code is kinda messy and there is most likely an easier way to create it but I understand it like this for now.
Any help is greatly appreciated. Thanks
JSFiddle Link : http://jsfiddle.net/Renay/g79ssyqv/3/
<p id="addTask"> <b><u> Tasks </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");
node.appendChild(removeTask);
}
You can simply assign event:
removeTask.addEventListener('click', function(e) {
node.parentNode.removeChild(node);
});
http://jsfiddle.net/g79ssyqv/6/
Edited the Fiddle... just try this
FiddleLink (Should work now, button and p-tag will be removed)
HTML
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
JS
var row = 0;
function addText(){
var input = document.getElementById('inputTask').value;
if(input != "")
{
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
node.setAttribute("id","contentP"+row);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.setAttribute("onClick", "deleterow("+ row +");");
node.appendChild(removeTask);
row++;
}
else
{
alert("Please insert a value!");
}
}
function deleterow(ID)
{
document.getElementById('contentP'+ID).remove();
}
Greetings from Vienna
Use this
// +your code
.....
node.appendChild(removeTask);
// + modify
removeTask.onclick = function(e){
var dom = this;
var p_dom = this.parentNode;
console.log(p_dom);
var parent_node = p_dom.parentNode;
parent_node.removeChild(p_dom);
}
Related
I'm new to html and learning through YouTube and such. I'm writing a JavaScript which allows me to show a custom window with checkboxes and textboxes (and labels) on it. I disabled the textboxes to begin with, but I would like them to be enabled when the corresponding checkboxes are checked.
I've searched on the internet for a solution, already tried using:
document.getElementById('chb1').onclick = function() { //my function };
or
document.getElementById('chb1').onclick = //my function;
but neither of them works.
function MyCheckboxWindow()
{
this.render = function(func,titel,dialog,checktext1)
{
var dialogboxbody = document.getElementById ('dialogboxbody');
dialogboxbody.innerHTML = dialog + ': <br>';
if(checktext1 != null)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = checktext1 + ': ';
document.getElementById('chb1').onclick = alert('');
}
else if(!checkboxCheck)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = "Other: : ";
document.getElementById('chb1').onclick = Change.ischanged('chb1');
checkboxCheck = true;
}
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="CheckboxWindow.ok(\''+func+'\')">Ok</button> <button onclick="CheckboxWindow.cancel()">Cancel</button>';
}
}
var CheckboxWindow = new MyCheckboxWindow();
function CheckboxChanged()
{
this.ischanged(id)
{
alert('');
}
}
var Change = new CheckboxChanged();
Just for info, there should be 6 of these checkboxes, but I left them out in this example. Also, in the "if", I replaced my function by an alert. The code in the if-clause produces an alertbox only when I open the custom window, clicking the checkbox doesn't do anything (but tick the box).
Writing it like I did in the "else if" in this example, doesn't produce anything at all, nor does function() { Change.ischanged('chb1'); } (like I said before).
Please tell me why this isn't working. There's probably a better way of adding these checkboxes as well, so if you know any, please let me know as well.
Hope this helps as a starting point:
//Dynamically create a checkbox, and add it to a div.
//appendChild() works for other types of HTML elements, too.
var div = document.getElementById("div");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkbox_1";
div.appendChild(checkbox);
var textbox = document.createElement("input");
textbox.type = "text";
textbox.disabled = true; //programmatically disable a textbox
div.appendChild(textbox);
//do something whenever the checkbox is clicked on (when user checks or unchecks it):
checkbox.onchange = function() {
if(checkbox.checked) { //if the checkbox is now checked
console.log("checked");
textbox.disabled = false;
}
else {
console.log("unchecked");
textbox.disabled = true; //programmatically disable a textbox
}
}
<div id='div'></div>
Thanks for your reply and I'm sorry for responding this late, I was quite busy the past 2 weeks and didn't have a lot of time.
I've tried to use your sample code but was unable to make it work. However, I was able to get it working by adding "onclick="Change.ischanged()" to the input in the if statement. I'm sure I tried something like that before, but I probably typed "CheckboxWindow" or "CheckboxChanged" instead of "Change" by mistake.
if(checktext1 != null)
{
dialogboxbody.innerHTML +='<br><input type="checkbox" id="chb1" onclick="Change.ischanged()"><label for="chb1" class="lbl" id="lbl1"></label>'
+ '<label for="txt1">€</label> <input type="text" id="txt1" value="0,00" disabled>';
document.getElementById('lbl1').innerHTML = checktext1 + ': ';
}
I know that adding the objects like this isn't the best way, but I seem to be having trouble trying to achieve my goal in your way.
I also changed "this.ischanged(id)" to "this.ischanged = function()" (I also made it so I don't need to pass the id anymore).
Try the OnClick event instead of the OnChange event for the checkbox.
//Dynamically create a checkbox, and add it to a div.
//appendChild() works for other types of HTML elements, too.
var div = document.getElementById("div");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "checkbox_1";
div.appendChild(checkbox);
var textbox = document.createElement("input");
textbox.type = "text";
textbox.disabled = true; //programmatically disable a textbox
div.appendChild(textbox);
//do something whenever the checkbox is clicked on (when user checks or unchecks it):
checkbox.onclick = function() {
if(checkbox.checked) { //if the checkbox is now checked
console.log("checked");
textbox.disabled = false;
}
else {
console.log("unchecked");
textbox.disabled = true; //programmatically disable a textbox
}
}
<div id='div'></div>
I am trying to remove an item every time it is clicked on but only a single item at a time (the item that was clicked on) when trying to make a 'to-do' list. I can easily remove all simultaneously but I am having a lot of issues trying to do it at an individual level. I thought this would work but hoping to get a second set of eyes on it.
var toDoCount = 0;
var todoarray = [];
window.onload = function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("#to-dos").prepend(linebreak);
$("#to-dos").prepend(value);
$("#to-dos").prepend(todoclose);
toDoCount++;
todoarray.push(value);
console.log(todoarray);
//to remove item from checklist
$(document.body).on("click", ".checkbox", function() {
var toDoNumber = $(this).attr("data-to-do");
$("#item-" + toDoNumber).remove();
});
});
}
HTML is below
<div class ="col-4">
<!-- To Do List -->
<form onsubmit= "return false;">
<span id = "todo-item" type = "text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
don't need the number, just the element.
change...
$("#item-" + toDoNumber).remove();
to...
$(this).remove();
e.g.
$(document.body).on("click", ".checkbox", function() {
$(this).remove();
});
I am trying to be able to add user input into an array. I cannot seem to figure out how to go about accomplishing this. I have spent hours trying to figure out exactly what to do. I also would like to have this "to do list" save to my local storage, I am equally frustrated with trying to figure out both of these issues.
Any advice or guidance on how to add to the array from user input and/or how to put this into local storage would be greatly appreciated. It has taken me quite some time to even get thus far. Thank you for all of your help! Greatly appreciated.
Javascript
var theList = [];
function todoList() {
var item = document.getElementById('todoInput').value;
var text = document.createTextNode(item);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var newItem = document.createElement("li");
newItem.appendChild(checkbox);
newItem.appendChild(text);
document.getElementById("todoList").appendChild(newItem)
return clear();
}
function clear() {
todoInput.value = "";
}
console.log(theList);
HTML
<h1>To Do List:<h1>
<input id="todoInput" type="text">
<button type="button" onclick="todoList()">Add Item</button>
</form>
<ol id="todoList">
</ol>
<script src="todo.js"></script>
To add the newly created list-item, just add theList.push(item) to your todoList() function.
To save the var theList = [] array to localStorage use:
localStorage.setItem("todoList", JSON.stringify(theList));
And use this to retrieve the localStroage object:
var storedTodoList = JSON.parse(localStorage.getItem("todoList"));
See the snippet below:
<h1>To Do List:</h1>
<input id="todoInput" type="text">
<button type="button" onclick="todoList()">Add Item</button>
<ol id="todoList">
</ol>
<script>
var theList = [];
function todoList() {
var item = document.getElementById('todoInput').value;
var text = document.createTextNode(item);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var newItem = document.createElement("li");
newItem.appendChild(checkbox);
newItem.appendChild(text);
document.getElementById("todoList").appendChild(newItem);
theList.push(item); // This adds the item to theList[]
//localStorage.setItem("todoList", JSON.stringify(theList)); // Set localStorage object
//var storedTodoList = JSON.parse(localStorage.getItem("todoList")); // Get localStorage object
console.log(theList);
return clear();
}
function clear() {
todoInput.value = "";
}
</script>
<!-- <script src="todo.js"></script> -->
Hope this helps.
If you don't mind using jQuery the following should be good enough - either way it's not very difficult to convert to JavaScript.
Here is a fiddle with a working to do list - https://jsfiddle.net/makzan/bNQ7u/
$('#add-btn').click(function(){
// get value from #name input
var val = $('#name').val();
// append the name to the list
$('#list').append("<li>" + val + " <a href='#' class='done-btn'>Done</a> <a href='#' class='cancel-btn'>Cancel Task</a></li>");
// reset the input field and focus it.
$('#name').val("").focus();
});
// correct approach
$('.done-btn').live( 'click', function() {
$(this).parent('li').addClass('done');
});
$('.cancel-btn').live( 'click', function() {
$(this).parent('li').fadeOut();
});
As you can see, the logic is to simply assign listeners which are handled much simpler in jQuery
I'm currently trying to add a jQuery function to a row of radio buttons. The problem is that I need to add dynamically many rows. Now For this example I only added 2 elements into the array of newNodes, but in my application newNodes can potentially have many different sizes.
So basically I want to add the Query function something like this:
$('#rowID input').on('change', function() {
alert($('input[name=i]:checked', '#rowID').val());
});
Where it exists inside the forloop and is added for each new row. "rowID" is a variable assigned to the unique row identifier and then use the loop iterator "i" as a way to distinguish the radio buttons for each row.
Here is the HTML:
<form id="createEdges" method="POST>
<fieldset>
<legend class="title">Modify the graph!</legend>
<table id="createEdgesTable">
</table>
<input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/>
</fieldset>
And Here is the Javascript:
newNodes = [];
newNodes.push(0);
newNodes.push(1);
//get HTML Table to add rows in
var edgeTable = document.getElementById("createEdgesTable");
//Create a table row for each node
for (var i in newNodes) {
var row = edgeTable.insertRow();
row.id = "node" + i;
//Show name of the node
var td = document.createElement('td');
var text = document.createTextNode(newNodes[i]);
td.appendChild(text);
row.appendChild(td);
//Choice for showing node
var td2 = document.createElement('td');
var radioButton1 = document.createElement('input');
radioButton1.type = "radio";
radioButton1.name = i;
radioButton1.value = "showNode";
td2.appendChild(radioButton1);
row.appendChild(td2);
//Choice for creating edge
var td3 = document.createElement('td');
var radioButton2 = document.createElement('input');
radioButton2.type = "radio";
radioButton2.name = i;
radioButton2.value = "createEdge";
td3.appendChild(radioButton2);
row.appendChild(td3);
//Choice for deleting node
var td4 = document.createElement('td');
var radioButton3 = document.createElement('input');
radioButton3.type = "radio";
radioButton3.name = i;
radioButton3.value = "removeNode";
td4.appendChild(radioButton3);
row.appendChild(td4);
var rowID = row.id;
}
$('#node0 input').on('change', function() {
alert($('input[name=0]:checked', '#node0').val());
});
JSFiddle: https://jsfiddle.net/nxexrq9y/
Any example on how to make this work for each row? I'm relatively new to JQuery and have been stuck on this problem for quite some time now. Thank you for your time and help!
Just change your script with following code.
$('tr[id^=node] input').on('change', function() {
alert(this.value);
});
Explanation:
Scripts find any tr whose id starts with node. this covers all your dynamically generated TRs. Further selection narrows down to only input element in each TR, and registers change event for that element. On that change event your have already got that element so you can easily access its value there.
Here is Js Fiddle Link
Further if you want to know clicked radio falls in which node, you can check out this js fiddle.
$('tr[id^=node] input').on('change', function() {
var row = $(this).parents('tr:first').get(0);
alert('Node: '+ row.id+ ' value:' + this.value);
});
Here is my JSFiddle: http://jsfiddle.net/kboucheron/XVq3n/15/
When I start a list of items and I click on "Clear", I would like to text input be cleared as well.I'm not able to clear the fields
<input type="text" placeholder ="Add List" id="listItem"/>
<button id="addButton">add Item</button>
<button id="clearButton">Clear Items</button>
<ul id="output"></ul>
clearButton.addEventListener("click", function(e) {
var text = document.getElementById('listItem').value;
var addItem = document.getElementById('output');
addItem.innerHTML = '';
text.value = '';
});
Just need to make this change here:
var text = document.getElementById('listItem');
You had this:
var text = document.getElementById('listItem').value;
What you are doing is getting the value of the input text, when you actually want the input element.
Also here is the updated fiddle: http://jsfiddle.net/XVq3n/16/
you are referring in your code to input's value, replace
var text = document.getElementById('listItem').value
with
var text = document.getElementById('listItem')
Ok, it's a really simple (but easy to make) error. Try this change and it should work:
clearButton.addEventListener("click", function(e) {
var text = document.getElementById('listItem');
var addItem = document.getElementById('output');
addItem.innerHTML = '';
text.value = '';
});
Basically, you did .value one too many times. Hope that helps.