reset input fields not working (Javascript) - javascript

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.

Related

Making array with input of textarea

I'm trying to capture the input of a textarea and converting it to an array but it is reading the whole input as one element and making array of length 1.
<html>
<textarea id="area"></textarea>
<input type="submit" onclick="won()">
<p id="one" style="display: none;"></p>
</html>
The js part displays a message of the length of the array.
var area = document.getElementById("area");
var lines = area.value.split("\n");
var pa = document.getElementById("one");
function won() {
pa.style.display = "block";
pa.innerHTML = lines.length;
}
What I'm trying to achieve with the whole thing is that. The multi line input is to be converted into an array with each new line being a new element. Then I loop through the array and if even one element doesn't pass a validation function, an exception message is displayed under the texarea.
Can someone kindly help me with this?
With your snippet, you're grabbing the value onload so it would be empty, it should be in the event where you grab the value. Also avoid inline event triggering, add the event via js.
var area = document.getElementById("area");
var button = document.getElementById("btn-submit");
var one = document.getElementById("one");
button.addEventListener('click', () => {
// get value
var lines = area.value.split("\n");
one.style.display = "block";
one.innerHTML = lines.length;
})
<textarea id="area"></textarea>
<button type="button" id="btn-submit">Submit</button>
<p id="one" style="display: none;"></p>
What I'm trying to achieve with the whole thing is that. The multi
line input is to be converted into an array with each new line being a
new element. Then I loop through the array and if even one element
doesn't pass a validation function, an exception message is displayed
under the texarea.
const area = document.getElementById("area");
const button = document.getElementById("btn-submit");
const error = document.getElementById("error");
const items = document.getElementById("items");
button.addEventListener('click', () => {
// get textarea value, remove emptys
const lines = area.value.split("\n").filter(Boolean);
// reset error and items dom
error.innerHTML = items.innerHTML = ''
// do your validation, could loop or use .some(), .includes()
if (!lines.length) {
error.innerHTML = 'Enter at least one item'
} else if (!lines.includes('cat')) {
error.innerHTML = 'Entered lines should include at least one cat'
} else {
// no errors
items.innerHTML = `${lines.length} items<br><ul><li>${lines.join('</li><li>')}</li></ul>`
}
})
<textarea id="area"></textarea>
<button type="button" id="btn-submit">Submit</button>
<div id="error"></div>
<div id="items"></div>
Simply put your line var lines = area.value.split("\n"); under the won function like below and you will get your total lines.
Example
var area = document.getElementById("area");
var pa = document.getElementById("one");
function won() {
var lines = area.value.split("\n");
pa.style.display = "block";
pa.innerHTML = lines.length;
}
You can check it here too, https://codepen.io/vadera-abhijeet/pen/yLPxLRY

Dynamically add Radio Button Labels - JavaScript

Having trouble getting the a label dynamically assigned to a radio button. all of the code is working except the innerHTML. Cannot spot why. Thanks in advance for any help.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
</form>
<br>
<button onclick="addRadio()">Add radio buttons!</button>
<script>
// This function will add a new Radio buttons to the above
count = 0;
function addRadio()
{
count++;
//Create input type
var myRadio = document.createElement("input");
var myName = document.createElement("testRadio");
var myBreak = document.createElement("br");
var myLabel = document.createElement("label");
var labelMessage = "Radio Button: " + count;
var labelId = "l" + count;
myRadio.setAttribute("type", "radio");
myRadio.setAttribute("name", "testRadio");
myRadio.setAttribute("value", "Radio Button: " + count);
myLabel.setAttribute("for", labelId);
myRadio.setAttribute("id", labelId);
document.getElementById('myForm').appendChild(myRadio);
document.getElementById('myForm').appendChild(myLabel);
document.getElementById('myForm').appendChild(myBreak);
document.getElementById('labelId').innerHTML = 'labelMessage';
}
</script>
</body>
</html>
The label element might not be inserted by the next line itself. It is better to do
myLabel.innerHTML = 'labelMessage';
As you have the element already in a variable.
There is a tiny error in the code.
Before the .innerHTML you get the element by id 'labelId' as a string.
You need to select with the labelID as a var so:
document.querySelector(`label[for="${labelId}"]`).innerHTML = labelMessage;

how to bind dynamically created button click events to dynamically created input in javascript?

I am very new to javascripts and trying to create a dynamic html form where there are multiple button, and each button click map to a corresponding form input. Here is my code:
<html>
<head>
<title>Create Group</title>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(){
$("#generate_form").click(function(){
var number = document.getElementById("number_of_groups").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var i;
for (i=1;i<=number;i++){
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
}
})
});
</script>
</head>
<body>
<h2>Create some group(s)</h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"/>
</body>
</html>`
So, the user would input number of groups to create and click 'Go' button, then the code should dynamically generate the form with the number the user choose. Each group of the form includes a input textbox and a 'Generate' button. When the button is clicked, the input textbox will show "hello world". However, the "hello world" only show up in the last input textbox no matter which 'Generate' button I click. So I changed the onclick function of the button to:
button.onclick = function(){ alert(thisID);};
Then I found that thisID is always the id of the last input textbox no matter which 'Generate' button I click. I guess that is because the binding of the click event does not happen till the script is done when 'thisID' would always be its latest value.
Would anyone please help me to realize the functionality I want? Thank you very much!
You would need to wrap the code within the for loop in a separate function, passing in the value of i as a parameter. This would create a closure, creating a new execution scope for your code. Otherwise what is happening is that your var is being hoisted, and is not exclusive to each iteration of the for loop, so your DOM is reflecting only the last value it was assigned.
for (i=1;i<=number;i++){
(function (i) {
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
})(i);
}
You can check out an article on closures here:
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
EDIT: As one of your commenters mentioned, you can also set your vars to 'let' to achieve a similar effect. This is because let scopes the variable to the current code block, rather than being hoisted to the scope of the function, so each for loop iteration has a private let variable. It is still recommended to get a good understanding of closures and how they work, however.
Since you are already using JQuery, you can reduce some of the logic.
Let me know if this helps-
<html>
<head>
<title>Create Group</title>
</head>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(()=>{
var txtGroup='<input type="text" id="txt_group_{0}" value="">';
var btnGroup='<button id="btn_group_{0}" type="button">Click Me</button>';
var container=$('#container');
$('#generate_form').click((e)=>{
var groupCount=parseInt($('#number_of_groups').val());
var idToStart=$('#container').children('div').length+1;
for(let i=idToStart;i< idToStart+groupCount;i++){
var divGroup=`<div id="div_group_${i}">`+
txtGroup.replace('{0}',i)+
btnGroup.replace('{0}',i)+`</div>`;
container.append(divGroup);
$('#btn_group_'+i).on('click',(e)=>{
console.log('#txt_group_'+i);
$('#txt_group_'+i).val('Hello World');
});
}
});
});
</script>
<body>
<h2></h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"></div>
</body>
</html>

Javascript To Do list app push to array/local storage

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

Removing items from a to do list using Javascript

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);
}

Categories