getting null value of button - javascript

I am creating a todo app. I create add button which is working perfectly fine. But, the trash button it keeps on returning null value.
I can not find solution on the google i didnt find the solution.
Can Anybody Help me here
var todoList = document.getElementById("todolist");
var addBtn = document.getElementById("add-btn");
var taskName = document.getElementById("task-name");
var trashBtn = document.getElementById("trash");
addBtn.addEventListener("click", addFunction);
function addFunction() {
var task = document.createElement("div");
task.classList.add("task");
var tname = document.createElement("li");
tname.setAttribute("id", "li-task");
var trash = document.createElement("BUTTON");
trash.setAttribute("id", "trash");
trash.innerHTML = '<i class="fas fa-trash"></i>';
tname.appendChild(trash);
task.appendChild(tname);
todoList.appendChild(task);
}
console.log(trashBtn);
console.log(addBtn);
<div class="main">
<header>
<h1>Doer's List</h1>
</header>
<div class="add-task">
<form>
<input type="text" id="task-name">
<button id="add-btn" type="button"><i class="fas fa-plus-circle"></i></button>
</form>
</div>
<div class="to-do-list">
<ul id="todolist"></ul>
</div>
</div>
Help Here

You need to get the Trash Button by id AFTER you've added it to the page.

I instead of creating new variable trashBtn, I used the variable which is define when creating Elemnt.

Related

display user input to list using javascript

I'm trying to create a to-do list app but i cant seems to append the user data to my list
html:
<div id="Html">
<input id="input-task" placeholder="New Task" >
<button id="add-btn" type="button" onclick="newTask()">
Add Tasks
</button>
</div>
<div>
<ul id="task-table">
<li>Task 1</li>
</ul>
</div>
separate javascript file:
const inputTask = document.getElementById('input-task').value;
var li = document.createElement('li');
var t = document.createTextNode('inputTask');
li.appendChild(t);
document.getElementById('task-table').appendChild(li);
}
inputTask is variable containing the text value but you using that as if it is string, remove the quotes around it.
I will also suggest you to avoid inline event handler, you can use addEventListener() instead like the following way:
document.getElementById('add-btn').addEventListener('click', newTask);
function newTask(){
const inputTask = document.getElementById('input-task').value;
var li = document.createElement('li');
var t = document.createTextNode(inputTask); //remove quotes here
li.appendChild(t);
document.getElementById('task-table').appendChild(li);
}
<div id="Html">
<input id="input-task" placeholder="New Task" >
<button id="add-btn" type="button">
Add Tasks
</button>
</div>
<div>
<ul id="task-table">
<li>Task 1</li>
</ul>
</div>
Try like this.
You should call newTask function and append child in it.
const inputTask = document.getElementById('input-task').value;
function newTask(){
var li = document.createElement('li');
var t = document.createTextNode(document.getElementById('input-task').value);
li.appendChild(t);
document.getElementById('task-table').appendChild(li);
document.getElementById('input-task').value="";
}
<div id="Html">
<input id="input-task" placeholder="New Task" >
<button id="add-btn" type="button" onclick="newTask()">
Add Tasks
</button>
</div>
<div>
<ul id="task-table">
<li>Task 1</li>
</ul>
</div>
Nothing wrong in your code!
Simple fixed this line
var t = document.createTextNode('inputTask');
Remove ('' quotes)
var t = document.createTextNode(inputTask);
And Final thing I don't know may be you have already done this but I want to mention this
Wrap this code inside the newTask() function
Example: -
function newTask(){
const inputTask = document.getElementById('input-task').value;
var li = document.createElement('li');
var t = document.createTextNode(inputTask);
li.appendChild(t);
document.getElementById('task-table').appendChild(li);
}

Add form items with javascript based on dropdown selection

I am building a recipe-database for myself (just to learn programming) and I've setup a base page with bootstrap, python, flask and sqlalchemy. I added the ingredients to the database and it is working fine. Now i can build recipes (another db.class) by adding these ingredients and combine them with the amount of them. I've prepared a form to setup all the required inputs.
For the ingredients i want to have a dropdown with all ingredients availabe in the db (done and working, see below). Now i want to add elements above in a container dynamically by selection of a dropdown-item. I staret by adding static elements first and it is working - when i use "onclick". This is what i have so far:
HTML of the dropdown:
<div id="container">
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Ingredient</label>
<div class="col-sm-2"><input
type="text"
class="form-control"
id="amount"
name="amount">
</div>
<label for="amount" class="col-sm-1 col-form-label">g / ml</label>
<div class="dropdown col-sm-2">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" id="Dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="addIngredient()">
Choose Ingredient
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
{% for ingredient in ingredients %}
<a class="dropdown-item" href="#">{{ ingredient.name }}</a>
{% endfor %}
</div>
</div>
</div>
This is the javascript I am calling:
function addIngredient() {
var container = document.getElementById("container");
var div_outer = document.createElement("div");
div_outer.setAttribute("class","form-group row");
container.appendChild(div_outer);
var label = document.createElement("label");
label.innerHTML = "Test";
label.setAttribute("class","col-sm-2 col-form-label");
div_outer.appendChild(label);
var div_inner = document.createElement("div");
div_inner.setAttribute("class","col-sm-2");
div_outer.appendChild(div_inner);
var input = document.createElement("input");
input.innerHTML = "Amount";
input.setAttribute("class","form-control");
div_inner.appendChild(input);
var label_unit = document.createElement("label");
label_unit.innerHTML = "g (ml)";
label_unit.setAttribute("class","col-sm-1 col-form-label");
div_outer.appendChild(label_unit);
var delete_btn = document.createElement("button");
delete_btn.setAttribute("type", "button");
delete_btn.setAttribute("class", "close");
delete_btn.setAttribute("onclick", "");
div_outer.appendChild(delete_btn)
var span = document.createElement("span");
span.setAttribute("aria-hidden", "true");
span.innerHTML = "×"
delete_btn.appendChild(span)
}
As a first step i wanted to replace the text of "label" with the selection of the Dropdown with that:
//Getting Value
var selObj = document.getElementById("Dropdown");
var selValue = selObj.options[selObj.selectedIndex].value;
//Setting Value
label.innerHTML = selValue;
Question 1: But as soon as I change the event from "onclick" to "onchange" it stops working. Why?
Question 2: How can i make the created items identifiable with a unique id, so that i can use the label-text to identify the ingredient-id and add them to the recipe-class. How can i generate that id?
Unfortunately i dont now much Java or HTML yet but i try to learn :)
Question 1:
The onchange attribute fires the moment when the value of the element is changed.
Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus. The other difference is that the onchange event also works on elements.
So if you want the onchange to be fired you should consider creating a drop-down list using HTML <select> Tag.
Question 2:
You can easily retrieve the id stored in your db of the item and set it in an attribute by your choice.

JQuery or JavaScript - get name of btn clicked

I have a quiz like slideshow that dynamically generates the questions and the list of answer options.
The answer options are of input type button and are generated dynamically from a table. The button name is also dynamically generated. The number of answer options is dymamic.
When a user clicks on an answer option I need to capture the name of the button.
I have tested out several interations of my code but am not successfully capturing the button clicked. Any input, insight is greately appreicated. Code is below. Just a quick callout - the HTML works without issue. I am using AMPSCRIPT for a Salesforce Makreting Cloud pages.
function btnAnswer(){
var btnClicked = $('.slide :button[clicked]');
var btnValue = $(btnClicked).val();
var btnName = $(btnClicked).attr("name");
var btnQuestion = btnName.substring(0, btnName.indexOf('A'));
btnQuestion = btnQuestion.substring(btnQuestion.indexOf('Q') + 1);
var btnAnswer = btnName.substring(btnName.indexOf('A') + 1);
updateScore(btnQuestion, btnAnswer);
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="slide">
<p class="question-p">%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'QuestionBackground'))=%%</p>
<h3 class="question-h3">%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'Question'))=%%</h3>
<div id="" class="question">
%%[
SET #answerOptions = BuildRowsetFromString(FIELD(ROW(#quizData,#qNum),'QuestionAnswerOptions'),'|')
SET #answerCount = RowCount(#answerOptions)
FOR #aNum = 1 to #answerCount DO
SET #answer = FIELD(ROW(#answerOptions,#aNum),1)
]%%
<div id="answerOptions">
<input value="%%=TreatAsContent(#answer)=%%" class="button-submit btnAnswer" name="Q%%=V(#qNum)=%%A%%=V(#aNum)=%%" type="button">
</div>
%%[
NEXT #aNum
]%%
<!-- BEGIN HIDE CRCT ANSWER FOR JS VALIDATION -->
<input name="crctAnswer" value="%%=V(FIELD(ROW(#quizData,#qNum),'questionCrctAnswerValue'))=%%" type="hidden">
</div>
<!-- END HIDE CRCT ANSWER FOR JS VALIDATION -->
<!-- HIDE/SHOW BASED ON SELECTION -->
<div id="" class="answer">
<div class="answer-title" style="display:none;"> <img class="icon" src="http://image.em.pge.com/lib/fe8c13727666037a72/m/6/general_cancel.png">
<h4 class="answer-h4-incorrect" style="display:none;">You are incorrect.</h4> </div>
<div class="answer-title" style="display:none;"> <img class="icon" src="http://image.em.pge.com/lib/fe8c13727666037a72/m/6/general_check.png">
<h4 class="answer-h4-correct" style="display:none;">You are correct!</h4> </div>
<div class="answer-explaination" style="display:none;">
<p class="answer-explaination" style="display:none;"><strong>The correct answer.</strong>%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'QuestionCrctAnswerText'))=%%</p>
</div>
</div>
</div>
Try using the jQuery button click handler
$(".btnAnswer").click( function() {
$(this).attr('name');
// or
this.name;
});
I guess you'd use Jquery like this:
$(".btnAnswer").click(function() {
// jQuery way
var btnValue = $(this).val();
var btnName = $(this).attr("name");
// Javascript way
var btnValue = this.value;
var btnName = this.name;
var btnQuestion = btnName.substring(0, btnName.indexOf('A'));
btnQuestion = btnQuestion.substring(btnQuestion.indexOf('Q') + 1);
var btnAnswer = btnName.substring(btnName.indexOf('A') + 1);
updateScore(btnQuestion, btnAnswer);
});

Event on created element

In my to-do-list deleteButton and doneButton work only on premade tasks.
They arent working on created elements li even that created elements are the same as premade. I am trying to use vanila js.
js:
var deleteButton = document.querySelectorAll('.delete');
for(i = 0; i < deleteButton.length; i++){
deleteButton[i].addEventListener('click', function() {
var li = this.parentNode;
li.classList.add('li-delete');
})
};
var doneButton = document.querySelectorAll('.done');
for (i = 0; i < doneButton.length; i++)
doneButton[i].addEventListener('click', function(){
if (this.classList.contains('done-green')) {
this.classList.remove('done-green');
} else {
this.classList.add('done-green');
}
});
var add = document.querySelector('.add');
add.addEventListener('click', function(){
var newLi = document.createElement('li');
var input = document.querySelector('input');
var ul = document.querySelector('ul');
var newP = document.createElement('p');
newLi.innerHTML = "<i class='icon-ok done'></i><i class='icon-trash delete'></i>"
newP.appendChild(document.createTextNode(input.value));
newLi.appendChild(newP);
ul.appendChild(newLi);
input.value = null;
})
html:
<div id="buttons">
<input type="text" placeholder="your new task...">
<button type="submit" class="add">add</button>
</div>
<div id="tasks">
<ul>
<li><i class="icon-ok done"></i>
<p>asd</p>
<i class="icon-trash delete"></i></li>
<li><i class="icon-ok done"></i>
<p>asd</p>
<i class="icon-trash delete"></i></li>
<li><i class="icon-ok done"></i>
<p>asd</p>
<i class="icon-trash delete"></i></li>
</ul>
</div>
You must attach listener after creation element.
Or you can attach listener to parent container of elements.
I think this answer can help you Attach event to dynamic elements in javascript

How to remove added item from a list?

I'm trying to learn JS and I decided to make a real app so that I can learn while I'm doing some stuff. I'm trying to make a TODO list app, I made the adding items but I can't figure out how to remove items when they got clicked.
Here's the code iteself:
MY TODO'S
<input id= "input" class="form-control" placeholder="Add items to your TODO list." type="text">
<button id="button" class="button btn btn-primary btn-block">Add</button>
<div class="items">
<ul id= "listGroup" class="list-group">
</ul>
</div> <!-- JS Items !-->
</div> <!-- End Div -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="app.js"></script>
JS:
var button1 = document.getElementById("button")
button1.addEventListener("click", addItem)
function addItem() {
let item = document.getElementById("input").value
let add = document.getElementById("listGroup")
let makeLi = document.createElement("li")
let makeText = document.createTextNode(item)
makeLi.className += "list-group-item"
let icon = document.createElement("i")
icon.className += "fa fa-times"
add.appendChild(makeLi).appendChild(makeText)
}
function revomeItem() {
}
var div1 = document.getElementById("div-01")
div1.addEventListener("click", removeItem);
function removeItem(e){
e.target.remove();
}
This should work..
makeLi.onclick = function(){
this.remove();
};

Categories

Resources