I want to delete all checked lists pressing the delete button but I don't know how - javascript

I'm learning Javascript and now I'm making to-do list.I've finished the basic one but I want to add the delete button which delete all the checked lists to my to-do list.
I've tried some ways that I came up with and they all failed and I cannot find the answer by googling.
How can I do this ? If there is someone who know, please teach me . I'd appreciated if you could show me how.
this is my code ↓ the error happened saying cannot read property 'parentElement' of null at Object.deleteAll
deleteAll: function() {
let taskListItem, checkBox, checkBoxParent;
for (i=0; i<this.taskListChildren.length; i++){
taskListItem = this.taskListChildren[i];
checkBox = taskListItem.querySelector('input[type = "checkbox"]:checked');
checkBoxParent = checkBox.parentElement;
checkBoxParent.remove();
}
document.getElementById('deleteChecked').addEventListener('click', () => {
tasker.deleteAll();
});
🙏
// this is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="css/styles.css">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
</head>
<body onLoad = "tasker.construct();">
<div class="tasker" id="tasker">
<div class="error" id="error">Please enter a task</div>
<div class="tasker-header" id="tasker-header">
<input type="text" id="input-task" placeholder ="Enter a task">
<button id="add-task-btn"><i class="fas fa-plus"></i></button>
</div>
<div class="tasker-body">
<ul id="tasks">
</ul>
</div>
<button id="deleteChecked">Delete</button>
</div>
<script src="js/main.js"></script>
</body>
</html>

You can use the jQuery library and solve it as follows.
Step 1) Define in your html button element:
<button id="button" onclick="reset()"> RESET </button>
Step 2) define the 'reset ()' function, like this
function reset()
{
$("input:chceckbox").removeAttr("chcecked");
}
Good luck!!

Related

What could be wrong with my keypress event?

I'm trying to make a weather app, and use the API from openweathermap, I copied the baseurl from the web like this but it's not currently working...
const api = {
key:"03173bc8739f7fca249ae8d681b68955"
baseurl:"https://home.openweathermap.org/api_keys"
}
const searchbox=document.querySelector('.search-box');
searchbox.addEventListener('keypress', setQuery)
function setQuery(evt){
if (evt.keyCode==13)
//getResults(searchbox.value)
console.log(searchbox.value)
}
So when I type in the search box, the console doesn't show anything...
This is my html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
<link rel="stylesheet" href="weather.css">
</head>
<body>
<div class="app-wrap">
<header>
<input type="text" autocomplete="off" class="search-box" placeholder="Search for a city...">
</header>
<main>
<section class="location">
<div class="city">HCM City, Viet Nam</div>
<div class="date">Friday 25 June 2021</div>
</section>
<div class="current">
<div class="tempt">15<span>°C</span></div>
<div class="weather">Sunny</div>
<div class="high-low">13°C / 16°C</div>
</div>
</main>
</div>
<script src="weather.js"></script>
</body>
</html>
Is there something wrong with the baseurl or something, can anybody tell me?
wrap the selector with " ";
const searchbox = document.querySelector(".search-box");
also correct your api obj:
const api = {
key: "03173bc8739f7fca249ae8d681b68955",
baseurl: "https://home.openweathermap.org/api_keys"
}
You missed to add single quote in querySelector.
const searchbox=document.querySelector('.search-box'); // Corrected
also you need to update the API object
const api = {
key:"03173bc8739f7fca249ae8d681b68955",
baseurl:"https://home.openweathermap.org/api_keys"
}

Javascript - looping through data with each click

I'm fairly new to Javascript I have been playing with some data fetching for the past few days. I created this very simple program (if you can even call it that), where if you click a button, it will generate a div with a random user (using jsonplaceholder API). My issue is, that whenever the button is clicked, it gives me all 10 users at once. I'd like it to give me one user with each click instead. As I said, I am fairly new to JS so I'm not sure how to aproach this (I guess some sort of a loop would be involved?). Any sort of advice, tips or anything would be welcomed ! Thank you !
Here is my code (Using Bootstrap 4 for styling and Axios for data fetching):
const mainButton = document.getElementById('mainButton');
const targetDiv = document.getElementById("targetDiv");
mainButton.addEventListener('click', () => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(function(response) {
let ourRequest = response;
renderData(ourRequest.data);
})
.catch(function(error) {
console.log(error);
});
function renderData(data) {
var stringHTML = "";
for (i = 0; i < data.length; i++) {
stringHTML += `
<div class="col-md-4">
<div class="card">
<div class="card-header">
User ID: #${data[i].id}
</div>
<div class="card-body">
<h4 class="card-title">${data[i].name}</h4>
<p class="card-text">Email - <em>${data[i].email}</em></p>
<p class="card-text">Phone - <em>${data[i].phone}</em></p>
<p class="card-text">Address - <em>${data[i].address.street}, ${data[i].address.city}, ${data[i].address.zipcode}</em></p>
</div>
</div>
</div>
`;
}
targetDiv.insertAdjacentHTML("beforeend", stringHTML);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="main.css">
<title>JSON Users</title>
</head>
<body>
<div class="container">
<div class="text-center my-5">
<h1 class="display-4">Random JSON Users</h1>
<p>This is a random user generator, click the below button to get a
random person!</p>
<button id="mainButton" class="btn btn-primary">Get User!</button>
</div>
<!-- Users -->
<div id="targetDiv" class="row">
</div>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="main.js"></script>
</body>
</html>
If I get it right that your GET method is asking for users, so response contains more that one user. This response you send to renderData method and there you generate your div for each user from response. I supouse to change your GET method to get only one user or send only one user to renderData method like ourRequest.data[0] from your current solution.

Execute javascript scripts after onclick and getvalue

I wanted to modify something in my code and don't really know how to make this work... my code is kinda huge so I am going to explain what I want with an exemple :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="stylesheets/application.css">
</head>
<body>
<label>Enter value : </label><input type="text" maxlength="512" id="reg_expr"/>
<div id="button">OK</div>
<div id="nfa"></div>
<script src="script1.js"></script>
<script src="script2.js"></script>
<script src="script3.js"></script>
</body>
</html>
So this is my HTML code, so what I want to do is NOT execute these 3 scripts until the user enters a value in the text input and clicks on OK. That value will be used in the js files, so i have to get the value after I click OK.
Can someone explain how this has to work ?
EDIT : problem was with jQuery that was not executing on Electron, solution : http://ourcodeworld.com/articles/read/202/how-to-include-and-use-jquery-in-electron-framework
For starters I would suggest changing; <div id="button">OK</div> to <button id="button">OK</button>.
I would then suggest to put each of those scripts into functions instead, then you can use the 'onClick' event from the button attribute as follows;
<button id="button" onClick="s1Func();s2Func();s3Func();">OK</button>
A better way would be to have one function call 'init' or something appropriate that then calls the 3 scripts/functions and have your buttons onClick even call that one initialization function.
JSFiddle Example:
https://jsfiddle.net/JokerDan/h7htk9Lp/
I would recommend you to load the scripts dynamically after you click on the button. This can be done via jQuery: https://api.jquery.com/jquery.getscript/
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="stylesheets/application.css">
<title>NFA2DFA</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<label>Enter value : </label><input type="text" maxlength="512" id="reg_expr"/>
<div id="button" onclick="loadScripts();">OK</div>
<div id="nfa"></div>
<script>
function loadScripts() {
// Is the input empty?
var value = $("#reg_expr").val();
if (value.length != 0) {
// Loads and executes the scripts
console.log(value); // Displays the value of the input field
$.getScript("script1.js");
$.getScript("script2.js");
$.getScript("script3.js");
}
}
</script>
</body>
</html>
You can use a button tag instead of input tag. I suggest you to use onClick event like this:
<button type="button" onclick="yourFunction()">Click me</button>
When the users click the button yourFunction() is call.
The result is this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="stylesheets/application.css">
<script src="script1.js"></script>
<script src="script2.js"></script>
<script src="script3.js"></script>
</head>
<body>
<label>Enter value : </label><input type="text" maxlength="512" id="reg_expr"/>
<button type="button" onclick="yourFunction()">Click me</button>
</body>
</html>

How to reload javascript without refreshing the page?

I have a webpage that links some javascript via tags. The script is amazon-localiser.js which will change an amazon link to one appropriate for the visitor. e.g. an Amazon.com link will swap to amazon.co.uk for a UK visitor or Amazon.de for a german visitor.It also appends to the link the relevant amazon affiliate link.
When the user lands on the page they click through some options (javascript) however by the time you reach an amazon link the page must be refreshed for the amazon-localiser.js script to work. I have tried using a page refresh in HTML but this sends me back to the very beginning of the questions. How do I reload the javascript without affecting the users location on the site?
The site is www.wfbsir.com, if you select "Scifi" then "Maybe" you will get to an amazon.com link, if you hover over it you will see it links to amazon.com if you refresh the page it will show you the link to your local store with an affiliate link appended.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>What book should I read?</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="app.css" />
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 text-right">
<button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>
</div>
</div>
</div>
<div class="container main">
<div class="row">
<div class="c12 text-center">
<h1 data-bind="text: queryData().text"></h1>
<h3 data-bind="text: queryData().subhead"></h3>
<h3><a data-bind="text: queryData().link, attr: {href: url}"></a></h3>
<div class="option-group" data-bind="foreach: queryData().answers">
<button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>
</div>
<button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
<button class="btn btn-default" type="submit" data-bind="click: buyBook, visible: navHistory().length > 1">Buy the book</button>
</div>
</div>
</div>
<div class="push"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script src="app.js?v=0.4.0"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="amazon-localiser.js"></script>
<script>
</script>
I have tried using jQuery getScript and also window.location.reload(); but neither reload just the javascript, the only thing that I can find to work is F5/Refresh.
I noticed that the amazon-localiser.js invokes the function findLocation onload of the page, as you can see below.
if (window.addEventListener) {
window.addEventListener("load", findLocation, false)
} else {
window.attachEvent("onload", findLocation)
}
So, a possible solution to your problem, could be to invoke this function again when you need to update your amazon link.
I tried invoking it from the console and it works, so try to invoke findLocation() manually when needed and see if it serves your scope.
Simone
You can add dynamically script on the page with some condition, for example:
var script = document.createElement('script');
var src;
if (true) {
src = 'amazon.co.uk';
} else {
src = 'amazon.com';
}
script.src = src;
document.head.appendChild(script);
As gnllucena told, you can view the question or there is the solution.
Build the loader function:
Put the following code in the document
<script type="text/javascript">
function LoadMyJs(scriptName) {
var docHeadObj = document.getElementsByTagName("head")[0];
var newScript= document.createElement("script");
newScript.type = "text/javascript";
newScript.src = scriptName;
docHeadObj.appendChild(newScript);
}
</script>
// place a button for reloading script.
<input type="button" name="reloadNewJs" value="Reload JavaScript" onClick="LoadMyJs('needed_script.js')">

Can't get JS function working properly

I've got this form with bootstrap but I can't find why it's not working properly ant I've no idea why.
HEAD>>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css"/>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/corrections.css" rel="stylesheet" type="text/css"/>
<script src="js/JQuery-2.1.1-min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
--> code here
</body>
HTML >>
<div class="col-lg-4">
<form class="form-inline well">
<div class="form-group">
<label class="sr-only" for="text">Some label</label>
<input id="text" type="text" class="form-control" placeholder="Text here">
</div>
<button type="submit" class="btn btn-primary pull-right">Ok</button>
<div class="alert alert-danger" style="display:none">
<h4>Error</h4>
Required amount of letters is 4
</div>
<div class="success alert-success" style="display:none">
<h4>Success</h4>
You have the required amount of letters
</div>
</form>
</div>
JS >>
<script>
$(function () {
$("form").on("submit", function () {
if ($("input").val().length < 4) {
$("div.form-group").addClass("has-error");
$("div.alert").show("slow").delay(4000).hide("slow");
return;
} else if ($("input").val().length > 3) {
$("div.form-group").addClass("has-success");
$("div.success").show("slow").delay(4000).hide("slow");
return;
}
});
});
</script>
the alert class shows everytime, any idea why?
The use of $("input") here is unusual. That selector will pull back all elements on the page that are <input>s, which is almost certainly not what you mean. (If there are other inputs on the page, you might get exactly what you're describing.) Use a more precise selector, like $("#text"), and maybe use debug to output the value of val().length so you know what you're evaluating.
(On a side note, "text" is not a very useful name for a text input, and your else-if seems redundant, but they probably aren't causing problems in your code.)

Categories

Resources