Clicking the button adds “undefined” instead of item - javascript

I just want my item to be added to the list.
I have tried putting "constant value" instead of candidate.value; then the value is getting displayed.
<div class="card-body">
<ul id="dynamic-list"></ul>
<input type="text" id="candidate" />
<button onclick="addItem()">add item</button>
<button onclick="removeItem()">remove item</button>
<script type="text/javascript">
function addItem() {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var li = document.createElement("li");
li.setAttribute('id', candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
function removeItem() {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var item = document.getElementById(candidate.value);
ul.removeChild(item);
}
</script>
</div>
The item should be added by clicking the “add item” button, but it is getting added as undefined.
Here’s a screenshot of the IDE:

Related

Unable to delete row using jquery which was dynamically created

I am creating new rows using jquery and want to delete that row when delete button is pressed. Adding new row part is working fine and the problem is in delete part. When I click on delete button then nothing happens. It doesn't even show alert which is written in code. It seems to me like delete button is not even getting pressed.
How can I delete that particular record when delete button is pressed?
JSfiddle is given below
https://jsfiddle.net/ec2drjLo/
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow">
</div>
As you have added the elements as a string, they are not valid HTML elements and that's why you can't add an event listener. You can add the click event to the document body and capture the event target, like
$(document).on('click', function (e){
if(e.target.className === 'deleteClass'){
//process next steps
}
}
You can try the demo below, not sure if it's the result you need, but the delete button works. Hope it helps!
let accountCount = 0;
$("#addAccount").click(function (e)
{
accountCount++;
let mystring = "<label class=\"ok\" id=\"[ID]\">[value]</label>";
let deleteString = "<button class=\"deleteClass\" id=\"deleteAccount"+ accountCount +"\">Delete Account</button>";
let currency = mystring.replace("[ID]", "currency"+ accountCount).replace("[value]", $("#currencyMain").val());
let amount = mystring.replace("[ID]", "amount"+ accountCount).replace("[value]", $("#amountMain").val());
$("#transactionRow").append(currency);
$("#transactionRow").append(amount);
let div = document.createElement('div');
div.innerHTML =deleteString;
$("#transactionRow").append(div);
$("#currencyMain").val('');
$("#amountMain").val('')
});
$(document).on('click', function (e)
{
if(e.target.className === 'deleteClass'){
var content = $("#transactionRow").html();
var pos = content.lastIndexOf("<label class=\"ok");
if(pos > 5)
$("#transactionRow").html(content.substring(0,pos));
else
alert("You cannot delete this row as at least one Account must be present");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow" style="border: 1px solid grey">
</div>

how to add an elemnt with text inside in Javascipt Dom

I work currently on my todo list.
I manged to get the text value from my input but i dont now how to add and element with the text value inside the text area. I want to add the text from my input inside the textarea in the undordered list.
Green is the input field and i want to get it from there in the white field
//query select to get button
let btn = document.querySelector('.add');
// selector to selct undorder list inside todotex
const ul = document.querySelector('.list');
//selector for input
const input = document.querySelector('input');
// eventlistner by button clicked
btn.addEventListener('click', function() {
var txt = input.value;
let li = document.createElement('li').innerHTML(txt);
ul.append(li);
});
<div class="card">
<div class="todoheader">TODO List</div>
<div class="todotext"></div>
<ul class="list">
</ul>
<div class="addtodo">
<button class="add" type="button"> + </button>
<input type="text" class="input" placeholder="add todo"></input>
</div>
</div>
As comment by #CBroe.
Replace innerHTML(txt);to innerHTML = txt;
https://jsfiddle.net/Memorynotfound/obhq8x50/
I found this JSFiddle that might help. Google is your best friend.
This guide explains it:
https://memorynotfound.com/dynamically-addremove-items-list-javascript/
function addItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var li = document.createElement("li");
li.setAttribute('id',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
function removeItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var item = document.getElementById(candidate.value);
ul.removeChild(item);
}
<ul id="dynamic-list"></ul>
<input type="text" id="candidate"/>
<button onclick="addItem()">add item</button>
<button onclick="removeItem()">remove item</button>

Tried to append span into list appendchild(span) it is throwing an error?

I'm the biginer . I have tried to append span into the list items which i have been dynamically created.But its not working. Within the function this code is working But Outside its not working...
Listcheck[i].appendChild(span); its not appending properly
var listcheck = document.getElementsByTagName("LI");
var span = document.createElement("SPAN");
for (var i = 0; i <= listcheck.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
span.textContent = "X";
span.className += "closeicon";
listcheck[i].appendChild(span);
}
function searchinput() {
var li = document.createElement("li");
var inputtext = document.getElementById("client_course").value;
var t = document.createTextNode(inputtext);
document.getElementById("myUL").appendChild(li);
li.appendChild(t);
}
<html>
<head>
<link rel="stylesheet" href="css/mainstyle.css">
<script src="JS/todo_JS.js"></script>
</head>
<header>
<div class="main">
<div class="checkportion">
<div class="chk_b">
<ul id="myUL">
</ul>
<input type="checkbox" class="check_class" id="check1">
<label for="check1">Javascript</label>
</div>
</div>
<div class="search_portion">
<Input type="text" id="client_course">
<input type="Submit" Value="add" onclick="searchinput()">
</div>
</div>
</header>
</html>
Your first block of code must not perform when script is loaded
because no one li in body at that time. Lis are added only when user
click button.
Where is your client_source?
var inputtext = document.getElementById("client_course").value;
3.Where is your MyUL?
document.getElementById("myUL").appendChild(li);
4.Your function searchinput creates li but does not append it to document. Therefore here:
listcheck[i].appendChild(span);
you have an error. listcheck[i] is undefined because no one li is appended.
UPD
It throws an error because this script performs one time, it is not a function that performs after some actions.
Page is loaded
Script performs (but function does not, because it performs only
after click on button)
3. Your first block does not see any LI so it
is undefined Solutions:
Create event and dispatch it to your
element
(developer.mozilla.org/ru/docs/Web/API/EventTarget/dispatchEvent)
Use MutationObserver

Making a counter in javascript To-do app

I have made a little javascript to-do app in order to get better at the language. I am trying to create a counter which increments each time a task is added to the ordered list, but it does not work. Here is my code:
var button = document.getElementById('add-button');
button.addEventListener('click', function() {
var item = document.getElementById('input').value;
var text = document.createTextNode(item);
var newItem = document.createElement('li');
newItem.appendChild(text);
document.getElementById('todoList').appendChild(newItem);
var count = 0;
count++;
document.getElementById('counter').innerHTML = count;
var removeTask = document.createElement('img');
removeTask.setAttribute('src', '/images/trash.jpg');
removeTask.setAttribute('id', 'trash');
removeTask.addEventListener('click', function() {
newItem.parentNode.removeChild(newItem);
});
newItem.appendChild(removeTask);
});
<div class="header">
<form>
<h2>Todo App</h2>
<p>Add a new todo</p>
<input type="text" id="input" placeholder="Enter an activity......">
<button type="button" id="add-button">Add Task</button>
</form>
</div>
<ol id="todoList">
<h1>Things to do:</h1>
<div id="counter">0</div>
</ol>
Right now it increments to 1 when one clicks but it ends there. I tried making a for loop that loops until the length of the newItem but that did not work at all. How can I make it increment on each time an item is added?
You need to define count outside of the scope of the event listener, otherwise you will always increment 0 by 1 for every item added (and 0+1 is always 1). Put the declaration outside of the listener, and increment that value:
var button = document.getElementById('add-button');
var count = 0;
button.addEventListener('click', function() {
var item = document.getElementById('input').value;
var text = document.createTextNode(item);
var newItem = document.createElement('li');
newItem.appendChild(text);
document.getElementById('todoList').appendChild(newItem);
count++;
document.getElementById('counter').innerHTML = count;
var removeTask = document.createElement('img');
removeTask.setAttribute('src', '/images/trash.jpg');
removeTask.setAttribute('id', 'trash');
removeTask.addEventListener('click', function() {
newItem.parentNode.removeChild(newItem);
});
newItem.appendChild(removeTask);
});
<div class="header">
<form>
<h2>Todo App</h2>
<p>Add a new todo</p>
<input type="text" id="input" placeholder="Enter an activity......">
<button type="button" id="add-button">Add Task</button>
</form>
</div>
<ol id="todoList">
<h1>Things to do:</h1>
<div id="counter">0</div>
</ol>

Show one div and hide the previous showing div

I have some links that will show a div when clicking it. When clicking another link, it should show the link's associated div and hide the previously shown div.
HTML
Text 1
Text 2
Text 3
<div id="text1" class="unhidden">
This will show up when the Text 1 link is pressed.
</div>
<div id="text2" class="hidden">
This will show up when the Text 2 link is pressed.
</div>
<div id="text3" class="hidden">
This will show up when the Text 3 link is pressed.
</div>
Javascript
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className='unhidden';
}
}
CSS
.hidden { display: none; }
.unhidden { display: block; }
How can I accomplish this?
Try with:
function unhide(divID) {
var unhidden = document.getElementsByClassName('unhidden');
for (var k in unhidden) {
unhidden[k].className='hidden';
}
var item = document.getElementById(divID);
if (item) {
item.className='unhidden';
}
}
You can do something like this :
function unhide(divID) {
var divs = document.getElementsByTagName('div');
foreach(var div in divs){
div.className = 'hidden';
if(div.id == divID)
div.className = 'unhidden';
}
}
Be careful with document.getElementsByTagName('div');, it will return you all divs on your document. You could adapt it using a wrapper.
For example :
HTML
<div id="wrapper">
<div id="text1" class="unhidden">
This will show up when the Text 1 link is pressed.
</div>
<div id="text2" class="hidden">
This will show up when the Text 2 link is pressed.
</div>
<div id="text3" class="hidden">
This will show up when the Text 3 link is pressed.
</div>
</div>
JS :
var divs = document.getElementById('wrapper').getElementsByTagName('div');
Try this http://jsfiddle.net/L79H7/1/:
function unhide(divID) {
var divIds = [ "text1", "text2", "text3" ];
for ( var i = 0, len = divIds.length; i < len; i++) {
var item = document.getElementById(divIds[i]);
if (item) {
item.className = divID == divIds[i] ? 'unhidden' : 'hidden';
}
}
}
You could also store in an array the names of the divs you want to hide and iterate over it when unhiding one:
var divs= new Array("text1", "text2", "text3");
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className='unhidden';
}
for (var i in divs){
if (divs[i] != divID){
item = document.getElementById(divs[i]);
if (item) {
item.className='hidden';
}
}
}
}
JSFiddle
You don't need exactly links for this, but if you insist change it to:
<a href="#" onclick='unhide("text3");'>Text 3</a>
Otherwise you can change it to:
<p onclick="unhide('text1')">Text 1</p>
<p onclick="unhide('text2')">Text 2</p>
<p onclick="unhide('text3')">Text 3</p>
<div id="text1" class="unhidden">
This will show up when the Text 1 link is pressed.
</div>
<div id="text2" class="hidden">
This will show up when the Text 2 link is pressed.
</div>
<div id="text3" class="hidden">
This will show up when the Text 3 link is pressed.
</div>
And your function should look like this to add or remove classes:
function unhide(id){
yourElement = document.getElementById(id);
if(yourElement.className == "unhidden"){
yourElement.className = "hidden";
}else{
yourElement.className = "unhidden";
}
}
demo
<div id="text1" class="hidden"> 1 </div>
<div id="text2" class="hidden"> 2 </div>
<div id="text3" class="hidden"> 3 </div>
.hidden{ display:none; }
#text1{ display: block; }
function show(id) {
var item = document.getElementById(id);
var all = document.getElementsByClassName('hidden');
for(var i=0; i<all.length; i++)all[i].style.display = 'none';
if(item)item.style.display = 'block';
}
you can use jquery try the code below and import the jquery library first
$('#text1').show();
$('#text2').hide();
it is the easiest way

Categories

Resources