html:
<header>
<h1>ENTER A TASK BELOW</h1>
<input type="text" id="task"><img id="add" src="add.png">
</header>
<div id="incomplete-tasks">
<h4>TO-DO LIST</h4>
<ul id="task-to-do">
</ul>
</div>
javascript / jquery:
$(document).ready(function() {
document.getElementById("add").addEventListener("click", function() {
var taskinput = document.getElementById("task").value;
if (taskinput) {
var tasktext = document.createTextNode(taskinput);
var list = document.createElement("li");
list.appendChild(tasktext);
var button = document.createElement("button");
button.setAttribute("class", "completed");
button.innerHTML = "X";
list.appendChild(button);
var toDoList = document.getElementById("task-to-do");
toDoList.insertBefore(list, toDoList.childNodes[0]);
document.getElementById("task").value = " ";
} else {
alert("Please enter a task");
}
});
$(document).on('click', "button.completed", function() {
$(this).closest("li").remove();
});
});
This is a simple to-do list I am working on. One of the things I have put in place is for an alert box to pop up if the user hits the "add" image/button without inputting anything into the field below "Enter a task".
However, something is wrong and it is allowing the user to add empty input values. I can not see what I am doing wrong here. Please can someone assit? Many thanks!
I made a small correction in your javascript/jquery code.In the if condition I added the trim() method to check if there is an empty characters string.
$(document).ready(function() {
document.getElementById("add").addEventListener("click", function() {
var taskinput = document.getElementById("task").value;
if ($.trim(taskinput)!== '') {
var tasktext = document.createTextNode(taskinput);
var list = document.createElement("li");
list.appendChild(tasktext);
var button = document.createElement("button");
button.setAttribute("class", "completed");
button.innerHTML = "X";
list.appendChild(button);
var toDoList = document.getElementById("task-to-do");
toDoList.insertBefore(list, toDoList.childNodes[0]);
document.getElementById("task").value = " ";
} else {
alert("Please enter a task");
}
});
$(document).on('click', "button.completed", function() {
$(this).closest("li").remove();
});
});
Related
I tried to create a function to delete individual list items by using addEventListener to the unordered list which calls a function that checks if the 'delete' button was clicked for that list item. If the 'delete' button was clicked, the function is supposed to delete the list item. But it doesn't seem to be working. Below is the code:
<!doctype html>
<html>
<head>
<meta charset='UTF-8'>
<link rel='stylesheet' href='listStyle.css'>
</head>
<body>
<h2 id='heading'>grocery list</h2>
<p>enter item into text box and press "enter" or click "submit".</p>
<p>to remove item, click "remove".</p>
<p>to reset list, click "reset".</p>
<input type = 'text' id = 'item' name = 'item'><br><br>
<button id = 'myBtn' onclick = 'myFunction()'>submit</button>
<button onclick = 'resetFcn()'>reset</button>
</form>
<script>
var str = document.getElementsByTagName('h2');
var strUpper = str[0].innerHTML.toUpperCase();
document.getElementById('heading').innerHTML = strUpper;
var res = document.createElement('ul');
res.setAttribute('id', 'myUL');
res.addEventListener('click', delBtn);
var input = document.getElementById('item');
input.addEventListener('keyup', function(event){
if(event.keyCode===13) {
document.getElementById('myBtn').click();
}
});
function myFunction() {
let x = document.getElementById('item').value;
if (x == '') {
alert ('enter input before submitting');
}
else {
document.body.appendChild(res);
var listItem = document.createElement('li');
const node = document.createTextNode(x);
var btn = document.createElement('button');
btn.innerHTML = 'remove';
btn.setAttribute('id', x);
btn.setAttribute('class', 'delete');
var att= document.createAttribute('style');
att.value = 'float: right';
btn.setAttributeNode(att);
listItem.append(x, ' ');
listItem.appendChild(btn);
res.appendChild(listItem);
item.value = '';
}
}
function resetFcn() {
while (res.firstChild) {
res.removeChild(res.firstChild);
}
}
function delBtn() {
if(event.target.classList.contains('delete')){
event.target.closest('listItem').remove();
}
}
</script>
</body>
</html>
Just add the click handler of the delete button inside your myFunction function:
function myFunction() {
let x = item.value;
if (x == '') {
alert ('enter input before submitting');
}
else {
const listItem = document.createElement('li');
listItem.innerText = x;
const btn = document.createElement('button');
btn.innerText = 'remove';
btn.addEventListener("click", (evt) => {
listItem.remove();
}); //this way you can delete the list item because it is in the same scope
listItem.appendChild(btn);
myUl.appendChild(listItem);
item.value = '';
}
}
This is outside your question but I would also clean up your code, remove the closing form tag, use const/let in stead of var. Do not use keyCode because it is deprecated, ...
I also inserted the ul element in your html:
<ul id="myUl">
</ul>
const myUl = document.getElementById("myUl");
For your reset function you can just set the innerHtml of the ul to an empty string in stead of looping through all the elements:
function resetFcn() {
myUl.innerHTML = "";
}
Hope this helped, good luck!
I'm trying to use this to create a message that states "Please enter a number" when you hit submit on a form and there's no number in the input for "If you would like to state a specific amount type it in the box below". It's doing absolutely nothing, so I don't know what's going on. I'm still in school and this is my first class with JavaScript so I would appreciate any help you can give.
Here is the JavaScript portion:
```
// test page form exception code - Chapter 4
function verifyFormCompleteness() {
var specificAmountBox = document.getElementById("specificamount");
var completeEntry = true;
var messageElement = document.getElementById("message");
var messageHeadElement = document.getElementById("messageHead");
var validity = true;
var messageText = "";
try {
if (specificAmountBox.value == "" || specificAmountBox.value == null){
window.alert = "Please enter a number in the specific amount box";
}
}
catch(message) {
validity = false;
messageText = message;
specificAmountBox.value = ""; // removes bad entry from input box
}
finally {
completeEntry
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = "";
alert("This is happening in the finally block");
}
if (validity = true) {
return submit;
}
}
```
Here is the HTML portion:
```If you would like to state a specific amount type it in the box below:<br>
<input type="number" id="specificamount" name="specificamount">
<h1 id="messageHead"></h1>
<p id="message"></p>
<br>
<br>
```
I have a 'like' button; and underneath the button, I can display the 'like count'.
However, I want the 'like count' value to be displayed on the actual button itself. For example, I want the button to say: "Like 5"
How can I display both text and a variable value on a button?
Maybe you can improving with this code that i did.
HTML
<form id = "form" method = "POST">
<input type = "submit" value = "Like" />
</form>
<br />
<div id = "clicks">
counter = <label id = "count">0</label> clicks !
</div>
JS
function CountOnFormSubmitEvent(form_id, _callback_)
{
var that = this, count = 0, callback = _callback_;
var form = document.getElementById(form_id);
if(form === null) { return null; }
var reset = function(){
count = 0;
};
form.addEventListener("submit", function(evt){
callback(evt, ++count, reset);
}, false);
}
//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
event.preventDefault();
if(count >= 10)
{
alert("Reseting the process");
reset_callback();
}
document.getElementById("count").innerHTML = count;
});
Here is the link Jsfiddle.
DEMO JSFIDDLE
I am trying to create a form which will take the user input to create a query for database. I have three buttons: And, Or, Run.
I am creating dynamic elements on click of buttons And and Or.
The div search_list is the container for containing the elements.
I need the form to be submitted on click of Run.
The weird thing is, whenever I click on any button the form gets submitted. How do I stop it ? Please let me know If you need more info.
Thanks
<html>
<head>
<script type="text/javascript">
var count = 0;
function loadfirst(){
count=1;
addFilter('');
}
function addFilter(flag){
var div = document.querySelector("#search_list");
tr = document.createElement("tr");
select = document.createElement("select");
var sear_value = document.createElement("input");
var and_or = document.createTextNode(flag);
tr.id='tr_'+count;
select.id='sl_'+count;
sear_value.id='sear_value_'+count;
select.options.add( new Option("user id","user_id", true,true) );
select.options.add( new Option("First name","first_name"));
select.options.add( new Option("Last name","last_name"));
select.options.add( new Option("Course","course"));
sear_value.type="text";
if(count<=1){
var bt_and= document.createElement("button");
bt_and.id='and';
var bt_label = document.createTextNode("And");
bt_and.appendChild(bt_label);
bt_and.addEventListener('click', function() {
addFilter('and');
return false;
});
var bt_or= document.createElement("button");
bt_or.id='or';
var bt_label = document.createTextNode("Or");
bt_or.appendChild(bt_label);
bt_or.addEventListener('click', function() {
addFilter('or');
return false;
});
}
else{
var bt_rem= document.createElement("button");
bt_rem.id='rem_'+count;
var bt_label1 = document.createTextNode("x");
bt_rem.appendChild(bt_label1);
var tr_id = 'tr_'+count;
bt_rem.addEventListener('click', function() {
var element= document.getElementById(tr_id);
element.parentNode.removeChild(element);
return false;
});
}
tr.appendChild(and_or);
tr.appendChild(select);
tr.appendChild(sear_value);
if(count<=1){
tr.appendChild(bt_and);
tr.appendChild(bt_or);
}
else{
tr.appendChild(bt_rem);
}
div.appendChild(tr);
count++;
}
function getFilter(){
alert();
}
</script>
</head>
<body onload="loadfirst()">
<span id='manage_stud_header' class= 'list_header'>
<label><?php echo $module_name;?></label>
<center>
<form>
<div id='search_list' class='search'></div>
<button id="run_filter" type="submit">Run</button>
</form>
</center>
</span>
</body>
</html>
The default type for buttons is "submit", so you have to explicitly say you want a plain button:
var bt_and= document.createElement("button");
bt_and.type = "button";
This way it won't submit the form when clicked. (unless of course you tell it to :))
you have to change
<button id = "run_filter" type = "submit" > Run </button>
in
<input id = "run_filter" type = "submit" value="Run" />
and then if the behaviour of click on button is forced to reload the page try to change button on other form element or see e.preventdefaulT of jquery
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);
}