In jQuery I want to be able to add and remove an element. I got the code for appending an element. Now I want to remove that same element when I click on it.
What is the best way to make this so called ToDo list in jQuery?
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
$("#toDoList").append("<p>" + newToDo + "</p>");
$("#newToDo").val(" ");
}
});
});
<h1>Todo list</h1>
<form name="form" action="#">
<input id="newToDo" type="text" name="in">
<button id="add">Add!</button>
</form>
<div id="toDoList"></div>
You should use event delegation to attach event to dynamically created elements like :
$("#toDoList").on('click', 'p', function() {
$(this).remove();
});
NOTE : Any button tag inside a form will be considered as submit button so it will refresh you page, to avoid that you should add type="button" to your button, like :
<button type="button" id="add">Add!</button>
Hope this helps.
$(document).ready(function() {
$("#add").click(function() {
var newToDo = $("#newToDo").val();
if (newToDo.length > 0) {
$("#toDoList").append("<p>" + newToDo + "</p>");
$("#newToDo").val(" ");
}
});
$("#toDoList").on('click', 'p', function() {
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Todo list</h1>
<form name="form" action="#">
<input id="newToDo" type="text" name="in">
<button type="button" id="add">Add!</button>
</form>
<div id="toDoList"></div>
You can simply store the element in a variable:
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
var anotherToDo = $("<p>" + newToDo + "</p>");
$("#toDoList").append(anotherToDo);
$("#newToDo").val(" ");
// later when you want to delete it
anotherToDo.remove();
}
});
});
Or give it an ID and then remove it using that:
$(document).ready(function () {
$("#add").click(function () {
var newToDo = $("#newToDo").val();
if(newToDo.length > 0){
var anotherToDo = $("<p>" + newToDo + "</p>").attr('id', '#someid');
$("#toDoList").append(anotherToDo);
$("#newToDo").val(" ");
// later when you want to delete it
$('#someid').remove();
}
});
});
Looks like it's already been answered for you, but here's an easy way to do what you want in jQuery:
// external.js
$(function(){
var todo = $('#todo');
function todos(){
$('#todos>li').click(function(){
todo.val($(this).text());
});
}
function remove(){
$('#todos>li').remove(":contains('"+todo.val()+"')");
}
function add(){
var tv = $.trim($('#todo').val());
if(tv !== ''){
remove(); $('#todos').append('<li>'+tv+'</li>'); todos(); todo.val('');
}
}
todo.focus(function(){
todo.val('');
});
$('#frm').submit(function(e){
add(); e.preventDefault();
});
$('#add').click(add);
$('#rmv').click(function(){
remove(); todos();
});
});
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:940px; padding:20px; margin:0 auto;
}
label{
margin-right:4px;
}
#todos>li{
cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Add Remove to List - jQuery</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='frm' name='frm'>
<label for='todo'>New To Do</label><input id='todo' name='todo' type='text' /><input id='add' name='add' type='button' value='add' /><input id='rmv' name='rmv' type='button' value='remove' />
<ol id='todos'></ol>
</form>
</div>
</body>
</html>
It the New To Do input (without the quotes, of course): Type "Go to the Store". Hit Enter. Type "Do my Hair". Hit Enter. Type "Go on a Bike Ride". Hit Enter. Click on the list now where you want to remove then press the remove button. If it was an accident, you can press add again, but focusing on the input clears the text, for your next input, with this design. It's also form ready for database implementation.
Related
On blur of an input field I want to run a validator. If validation fails I need to set focus back in to the field and cancel out the next intended operation.
I am able to achieve the first part, to set the focus back into the field, but the next operations (button click, link click) are also executing. I need help in restricting actions if validation fails in blur.
Following is the code snippet replicating this behavior. Focus on the field and then try to click on the link/button. Their callbacks are getting executed, which I need to restricted if there is an error on blur event handler of the input field.
$(document).ready(function() {
$('.form-control').blur(function(e) {
var $this = jQuery(this),
hasError = true;
if (hasError) {
setTimeout(function() {
$this.focus();
}, 0);
return false;
}
});
$('.link').click(function(e) {
console.log('link clicked');
});
$('.button').click(function(e) {
console.log('button clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="text" class="form-control" />
<br/><br/>
Link
<br/><br/>
<button class="button">Submit</button>
</div>
You can try with pointer-events
$(document).ready(function() {
$('.form-control').blur(function(e) {
var $this = jQuery(this),
hasError = $this.val().trim()== ''?true:false;
if(hasError) {
setTimeout(function() {
$this.focus();
}, 0);
$('.link, .button').css('pointer-events','none');
}
else $('.link, .button').css('pointer-events','');
});
$('.link').click(function(e) {
console.log('link clicked');
});
$('.button').click(function(e) {
console.log('button clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="container">
<input type="text" class="form-control" />
<br/><br/>
Link
<br/><br/>
<button class="button"> Submit</button>
</div>
</body>
</html>
So I've been making a really simple ToDo list using HTML, JS and CSS and the only thing left is to show the user how many tasks there are and how many are completed. E.g. if there is 3 completed ones and 7 tasks in all, it should output 3/7. I've been trying to do this with some eventlisteners and stuff, but can't get it to work... How can I do this using the ouput element in the HTML and JS?
var button = document.getElementById('button')
var ul = document.getElementById('todo')
var output = document.getElementsByName('result')
button.addEventListener("click", addTask);
button.addEventListener("click", function(event) {
event.preventDefault()
})
function addTask() {
var checkbox = document.createElement("INPUT")
checkbox.setAttribute("type", "checkbox");
var label = document.createElement("LABEL");
var li = document.createElement("LI");
var task = document.createTextNode(document.getElementById('task').value);
label.appendChild(task)
li.appendChild(label)
li.insertBefore(checkbox, li.childNodes[0])
ul.appendChild(li)
var date = new Date()
tasks.push({
text: document.getElementById('task').value,
date: date
})
}
var tasks = []
console.log(tasks)
#todo {
list-style-type: none;
margin-left: 0;
padding-left: 0;
}
input[type=checkbox]:checked + label {
text-decoration: line-through;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
</head>
<body>
<header>
<h1>To-do list</h1>
</header>
<form class="" action="" method="">
<input type="submit" name="button" value="Add task" id="button">
<input type="text" name="input" id="task" autofocus>
<output name="result"></output>
<ul id="todo"></ul>
</form>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
This approach adds two elements to show completed todos and the total count. Likewise, binds the event change to every newly created checkbox to capture when the user clicks on them.
var button = document.getElementById('button')
var ul = document.getElementById('todo')
var output = document.getElementsByName('result')
var total = document.getElementById('total')
var completed = document.getElementById('completed')
button.addEventListener("click", addTask);
button.addEventListener("click", function(event) {
event.preventDefault();
});
function addTask() {
var checkbox = document.createElement("INPUT");
checkbox.setAttribute("type", "checkbox");
// Add one more todo in total count.
total.textContent = +total.textContent + 1;
//Thrigger the completed event
checkbox.addEventListener("change", function(event) {
if (this.checked) completed.textContent = +completed.textContent + 1;
else completed.textContent = +completed.textContent - 1;
});
var label = document.createElement("LABEL");
var li = document.createElement("LI");
var task = document.createTextNode(document.getElementById('task').value);
label.appendChild(task)
li.appendChild(label)
li.insertBefore(checkbox, li.childNodes[0])
ul.appendChild(li)
var date = new Date()
tasks.push({
text: document.getElementById('task').value,
date: date
});
}
var tasks = []
console.log(tasks)
#todo {
list-style-type: none;
margin-left: 0;
padding-left: 0;
}
input[type=checkbox]:checked+label {
text-decoration: line-through;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
</head>
<body>
<header>
<h1>To-do list</h1>
</header>
<form class="" action="" method="">
<input type="submit" name="button" value="Add task" id="button">
<input type="text" name="input" id="task" autofocus>
<output name="result"></output>
<p>My completed todos: <span id='completed'>0</span> / <span id='total'>0</span> </p>
<ul id="todo"></ul>
</form>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
The reason why its not working is because you put it inside a form. Forms should be used only when you want to submit a POST or PUT request to the server running the website. When the button of "submit" is pressed the browser refreshes the page because it sent a POST request to the server, and it responded (most likely with a 404 - Not Found). So firstly, you have to remove the form.
Second, I advise you strongly to use jQuery instead of using regular DOM manipulation methods. It is way faster, more scalable and not to mention easier to read and write. Here is a Plunker with your code that I adapted slightly to make it work.You can view it here.
var tasks = []
var button = $('#button')
var ul = $('#todo')
var output = $('#result')
button.click(function() {
addTask();
});
function addTask() {
var li = $('<li/>');
var checkbox = $('<input/>')
.attr('type', 'checkbox');
var taskText = $('#task').val();
var label = $('<label/>')
.html(taskText);
li.append(checkbox);
li.append(label);
ul.append(li);
var now = new Date()
tasks.push({
text: taskText,
date: now
});
console.log(tasks);
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
</head>
<body>
<header>
<h1>To-do list</h1>
</header>
<div>
<button name="button" value="Add task" id="button">Add task</button>
<input type="text" name="input" id="task" autofocus>
<output name="result"></output>
<ul id="todo"></ul>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
While following a tutorial, I see style sheet is not applied to clicked element in the list. What Could be the possible reason?
The following sample works this way if some string is added to text box and then button is clicked, a new item gets added to list. If item in the list is clicked it should be stroked through.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#taskText').keydown(function (evt) {
if (evt.keyCode == 13) {
addTask(this, evt);
}
});
$('#addTask').click(function (evt) {
addTask(document.getElementById('taskText'), evt);
});
// following statements not working
$('#tasks li').live('click', function(evt) {
$(this).addClass('done');
});});
function addTask(textBox, evt) {
evt.preventDefault();
var taskText = textBox.value;
$('<li>').text(taskText).appendTo('#tasks');
textBox.value = "";
};
</script>
<style type="text/css">
.done{
text-decoration:line-through;
}
</style>
</head>
<body>
<ul id="tasks">
</ul>
<input type="text" id="taskText" />
<input type="submit" id="addTask"/>
</body>
</html>
The live() function was removed in jQuery 1.7 and does not exist at all in jQuery 2.x.
If you check your browser's developer console, chances are you'll see an error message along those lines.
$(document).ready(function() {
$('#addTask').click(function() {
var taskText = $('#taskText').val();
var li = $('<li>' + taskText + '</li>');
$('ul#tasks').append(li);
$('#taskText').val('');
$(li).click(function() {
$(this).toggleClass('done');
});
});
});
li {
font-family: arial;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
}
.done{
text-decoration: line-through;
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="tasks">
<!-- List Goes Here... -->
</ul>
<!-- Textbox / Input Buttons -->
<input type="text" id="taskText" />
<input type="submit" id="addTask"/>
</body>
</html>
$('#tasks li').click(function(){
$(this).addClass('class-name');
};
should work. Check to make sure all your syntax is correct (ie. no random semicolons)
As mentioned by ceejayoz . The live() function was removed in jQuery 1.7 and does not exist at all in jQuery 2.x.
The reason your click on the list was not working is better explained on this question: Click event on dynamically generated list items using jquery
here's what the code could look like for you
$(document).ready(function() {
$('#taskText').keydown(function(evt) {
if (evt.keyCode == 13) {
addTask(this, evt);
}
});
$('#addTask').click(function(evt) {
addTask($('#taskText'), evt);
});
$('#tasks').on('click', 'li', function(evt) {
$(this).addClass('done');
});
});
function addTask(textBox, evt) {
evt.preventDefault();
var taskText = textBox.val();
$('<li>').text(taskText).appendTo('#tasks');
textBox.val("");
};
.done {
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tasks">
</ul>
<input type="text" id="taskText" />
<input type="submit" id="addTask" />
I'm doing a schoolproject, trying to do an list of things you need to buy.
The problem is, i can't write more than one time and add to the list, and i can't figure out why.
(It's nowhere near done.) (i have to diffrent javascript files)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="main.css" type="text/css" rel="stylesheet">
<title>Inköpslista</title>
</head>
<body>
<div id="kol1" class="kol">
<h1>Inköp</h1>
<input type="image" src="img/button.png" alt="Submit" id="storknapp" onclick="klickaKnapp('skriva')"/>
<input type"text" id="skriva" placeholder="Skriv din vara här!"/>
<input type="image" id="knapp" src="pluss.png" alt="Submit"/>
</div>
<div id="kol2">
<ul id="listaavvara"></ul>
</div>
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
</body>
</html>
function laggtill(cool, namnVara) {
var vara = document.createElement("li");
vara.innerText = namnVara;
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if(!namnVara|| namnVara =="" || namnVara == " " ){
return false;
}
laggtill(document.getElementById("listaavvara"), namnVara);
};
javascrpit 2:
function klickaKnapp(x){
var skrivrutan = document.getElementById(x), maxH="100px";
if(skrivrutan.style.height == maxH){
skrivrutan.style.height = "0px";
} else {
skrivrutan.style.height = maxH;
}
}
HOPEFULLY YOU KNOW WHAT I MEAN! (my pictures are not here)
Because
var button = document.getElementById("knapp");
button.onclick = function() { ... }
overrides the inline event handler. You need to attach events with addEventListener
button.addEventListener("click", function(){...}, false);
Your example works for me on fiddle: http://jsfiddle.net/7zjb86ab/
So this looks like there is something wrong with your imported scripts
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
Are those the two files with your javascript snippets inside?
You could also try to replace
var button = document.getElementById("knapp");
button.onclick = function() {
with
function addItem() {
and then add the function as onclick attribute like you do with the klickaKnapp function
<input type="image" id="knapp" src="pluss.png" alt="Submit" onclick="addItem()" />
Here is my HTML -
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> My Shopping List</title>
<link rel="stylesheet" type="text/css" href="shoppinglist.css">
<link href='http://fonts.googleapis.com/css?family=Quicksand:300,400|Advent+Pro:300' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="shoppinglist.js"></script>
</head>
<body>
<div class="container">
<p id="shoppinglist"> My Shopping List App</p>
<input type="text" name="user" class="entertext">
<input type="button" value="Enter" class="returnkey">
<br>
<br>
<ol></ol>
</div>
</body>
</html>
Here is my JavaScript -
$(document).ready(function () {
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$("input[type='text']").keyup(function(event) {
if(event.keyCode == 13) {
$("input[type='button']").click();
}
});
$("ol").on("click", "input[type='checkbox']", function() {
$(this).parent().remove();
});
});
How do I create JavaScript for someone whose entering empty? So something to prevent them from empty text input?
You can check if the value of the text input is equal to a blank string:
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
//start new code
if ($.trim(item) === '') {
alert("Please Enter Something!");
return false;
}
//end new code
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$.trim() removes any extra white-space, to make sure the input doesn't just have white-space as a value.
Something like this?
$('.returnkey').on('click', function() {
var string = $.trim($('.entertext').val());
if (string == '') {
alert('Field is empty');
return false;
}
}