Why does my delete button does not delete the card - javascript

I want to delete the card when we click on the delete button after adding a TODO note
I have created a website which uses localstorage to store notes and display when clicking the create TODO button and it all works but when I click the delete button after the note is created (You have to create a TODO first) it does not delete the div itself
I want to delete the card when we click on the delete button
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
if (key != "" && value != "") {
iHTML = ""
localStorage.setItem(key, value)
iHTML += `
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${key}</h5>
<p class="card-text">${localStorage.getItem(key)}</p>
<button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
</div>
</div>
`
document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>

The error is thrown on this line onclick='${key}.innerHTML=""'. You will want to first remove the item from local storage e.g: localStorage.removeItem('${key}') and then remove the html. Theres many way of achieveing this but this.parentElement.parentElement.remove() should be sufficient
The complete button should look something like <button type="button" id="note" onclick="localStorage.removeItem('${key}'); this.parentElement.parentElement.remove()" class="btn btn-danger '${key}'">Delete</button>
Heres a working example:
https://jsfiddle.net/qt83bshd/

Well, i post you a simple solution for your problem.
Instead of use innerhtml to introuce your todos, yo can create the elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
/* add css in this poiint to optimize code*/
.card {
width: 18rem;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
// collect the div that contains all the todos
let alltodo = document.querySelector(".all-todo");
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
// and if it any todo create the card
if (key != "" && value != "") {
localStorage.setItem(key, value)
// with create element we can create the card more easy
var todo = document.createElement("div");
todo.setAttribute("class", "card");
var button = document.createElement("button");
button.textContent = "eliminar";
var titulo = document.createElement("h5");
titulo.textContent = key;
button.onclick = () => {
console.log(button.parentElement.remove())
// in this point we can also remove the todo from the local storage wih localstorage.removeItem()
}
// introduce all items in dom
todo.appendChild(titulo)
todo.appendChild(button);
alltodo.appendChild(todo);
// iHTML = ""
// localStorage.setItem(key, value)
// iHTML += `
// <div class="card" style="width: 18rem;">
// <div class="card-body">
// <h5 class="card-title">${key}</h5>
// <p class="card-text">${localStorage.getItem(key)}</p>
// <button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
// </div>
// </div>
// `
// document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>

Related

I want to display the result that I fetched from this weather API(https://openweathermap.org/current) but when i type the city name i get no response

I want to display the result that I fetched from this API (https://openweathermap.org/current) but when i type the city name i get no response. I could not figure out where the error is happening.
This api takes the name of the city and gets you weather details, here i am only interested in displaying the weather (weather[0].main) and the temperature (main.temp).
The result will be displayed in the tag with id "result".
Here's my code,
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Weather</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">
<img src="image_prev_ui.png" width="85" alt="image not available"/>
myProject
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="quote.html">Motivationl Quotes</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="weather.html">Weather</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid mt-5">
<div class="jumbotron jumbotron-fluid mt-5">
<div class="text-center text-white mt-5">
<h1 class="display-4">Find Weather</h1>
<p class="lead"><em>Enter the name of any city for weather information</em></p>
<form id="forminput">
<input type="text" class="form-control text-center mt-5" id="city" placeholder="Example: Kolkata">
<button class="btn btn-outline-light btn-lg mt-5" type="submit">Submit</button>
</form>
<p id="result" class="text-white text-center fst-italic mt-5"></p>
</div>
</div>
</div>
<footer class="bg-dark text-center text-lg-start">
<div class="text-center text-white p-3" style="background-color: rgba(0, 0, 0, 0.2);">
© 2021 Copyright:
<a class="text-muted" href="index.html">myProject.com</a>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>
And here's the js jquery
$(document).ready(funtion(){
$("#forminput").submit(function(event){
performSearch(event);
});
});
function performSearch(event){
var request;
event.preventDefault();
request = $.ajax({
url :'https://api.openweathermap.org/data/2.5/weather',
type : "GET",
data : {
q : $("#city").val(),
appid : '2c476e538ecec946a44e8cc19a3effde',
units : 'metric'
}
});
request.done(function(response){
formatSearch(response);
});
}
function formatSearch(jsonObject){
var city_name = jsonObject.name;
var city_weather = jsonObject.weather[0].main;
var city_temp = jsonObject.main.temp;
$("#result").text("Weather now in "+city_name+" is "+city_weather+" and the temperature is "+city_temp+" Celcius.");
}
Hi #Abhishek Can you try to send your request like this
let url = `https://api.openweathermap.org/data/2.5/weather?q=${$("#city").val()}&appid=2c476e538ecec946a44e8cc19a3effde&units=metric`;
let request = $.ajax({
url :url,
type : "GET"
});

How to properly remove the contents inside of a modal

The heights of each building from West (left) to East (right) is given in an integer array. You have to tell which buildings will be able to see the sunset. I've written a program that will be able to tell which buildings can view the sun from left to right. The problem I'm having is currently with the modal. I'm trying to clear the information that is inside the modal use clearContents(). At first, I was using clear() till i noticed that clear() is a global method. I then tried using document.getElementById("results").innerHTML = " ";.
the entire website is provided but the code snippet is below.
https://zacharyhadjahsunsethills.netlify.app/
let sunsetOrder = ["Building 1 will always view the sunset!"];
function BeginFunction(){
//wire up all the data to the building variables
let building1 = parseInt( document.getElementById("input1").value )
let building2 = parseInt( document.getElementById("input2").value )
let building3 = parseInt( document.getElementById("input3").value )
let building4 = parseInt( document.getElementById("input4").value )
let building5 = parseInt( document.getElementById("input5").value )
//User Input validation
if(building1 == null || building2 == null || building3 == null || building4 == null ||
building5 == null){
document.getElementById("results").innerHTML = `You must input numbers for all buildings`
//clear data
document.getElementById("results").innerHTML = ``
}else{
//Put all the buildings into an array
let buildingsArray = [building1, building2, building3, building4, building5]
//You will need to use nested for loops. Nested for loops are how you can properly
//compare elements inside of an array with eachother.
//Loop starts at one because it will be the loop that is compared to all the
//previous buildings that are infront of it
for (let currentBuilding = 1; currentBuilding < buildingsArray.length; currentBuilding++) {
//will be kept false UNTIL you find the tallest building
//once tallest building is found, it will be switched to true
let tallest = false;
//this loop starts at one because it will need to stay before the position of the
//current building. It needs to stay before current building to properly compare
//which building is taller. That is why the middle condition is
// previousBuilding < currentBuilding
for (let previousBuilding = 0; previousBuilding < currentBuilding; previousBuilding++) {
//if any of the previous building are taller than the building that is currently being compared with,
//then change the bool to true
if(buildingsArray[previousBuilding] >= buildingsArray[currentBuilding]){
tallest = true;
break;
}else{
continue;
}
}
if(tallest == false){
sunsetOrder.push("Building #" +(currentBuilding + 1)+ " can view the sunset")
}
else{
sunsetOrder.push("Building #" +(currentBuilding + 1)+ " can't view the sunset")
}
let results = sunsetOrder.join("<br>")
document.getElementById("results").innerHTML = `${results}`
}
}
}
function clearContents(){
document.getElementById("results").innerHTML ="";
}
.navbar-dark .navbar-nav .active>.nav-link{
color:white;
}
.navbar-dark .navbar-nav .nav-link{
color:black;
}
.navbar .navbar-brand{
color:black;
}
.container {
width:960px;
height:640px;
position:absolute;
top:50%;
left:50%;
margin-top:-320px;
margin-left:-480px;
}
body{
background-image: url("img/SunsetHillsBackground.png");
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
::selection{
background-color: #F0E440;
}
#ResultsHeader{
background-color: #F0E440;
}
#ResultsFooter{
background-color: #F0E440;
}
#ResultsBody{
background-color:#f3eb7b
}
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fizz Buzz Coding Challenge (Implementing the Meta Strat</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/prism.css">
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-dark" style="background-color: #F0E440;">
<a class="navbar-brand" href="index.html">SunsetHills</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId"
aria-expanded="false" aria-label="Toggle navigation"></button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item">
<a class="nav-link" href="index.html">🌒Home </a>
</li>
<li class="nav-item">
<a class="nav-link active" href="solve.html">🌓Solve <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="code.html">☀Code</a>
</li>
<li class="nav-item">
<a class="nav-link" target="_blank" href="https://zacharyhadjah.netlify.app/">🌗Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" target="_blank" href="https://github.com/zhadjah9559/SunsetHills">🌘Github</a>
</li>
</ul>
</div>
</nav>
<div class="container pt-5 align-items-center">
<div class="row justify-content-center pb-4">
<img src="img/SunsetHills.png" alt="Sunset Hills logo" id="Logo" class="responsive" >
</div>
<hr/>
<div class="row pt-5 mt-5">
<div class="col-md form-group">
<input class="form-control" id="input1" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input2" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input3" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input4" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input5" placeholder="Enter Height" type="number"/>
</div>
</div>
<div class="row justify-content-center pt-2">
<label>
<button class="btn btn-primary" type="submit" onclick="BeginFunction()"
data-toggle="modal" data-target="#ResultsModal">
Submit
</button>
</label>
</div>
</div>
<!--Results Modal-->
<div class="modal fade" id="ResultsModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header justify-content-center" id="ResultsHeader">
<h1 id="ResultsHeaderH1">Results</h1>
</div>
<div class="modal-body" id="ResultsBody">
<div id="small-dialog2" class="white-popup zoom-anim-dialog text-center">
<div id=results></div>
</div>
</div>
<div class="modal-footer justify-content-center" id="ResultsFooter">
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="clearContents()">Close</button>
</div>
</div>
</div>
</div>
<!--Results Modal-->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="js/custom.js"></script>
<script src="js/prism.js"></script>
</body>
</html>
If you inspect the content of the web with the devs tools you can see that your function clearContents() is working correctly.
The problem here is that you ain't clearing your sunsetOrder array, so every time that you do click on the submit button you are pushing new elements to it and showing all the array in the modal.
To solve this you can add the following code to your clearContents function:
function clearContents() {
document.getElementById("results").innerHTML ="";
sunsetOrder = [];
}

how to clear search result while click in search button

I made a song and a lyric searching page. The first time search is working well but while I click in the search button the previous result remains and also search results also shown on the page.
Now I want to disappear the result while searching for another song or lyric.
And also I want to make the search the result same style but I don't get results as I wanted.
const text = document.getElementById('text');
const search = document.getElementById('search');
const result = document.getElementById('result');
// api url
const api= 'https://api.lyrics.ovh';
// song lyrics
function getLyrics (artist, title) {
let url = `${api}/v1/${artist}/${title}`
fetch(url)
.then(res => res.json())
.then(singerLyrics => {
const lyrics = singerLyrics.lyrics;
const getLyric = document.getElementById('getLyric');
getLyric.innerHTML = `<h2 class="text-success mb-4">${artist} - ${title}</h2>
<pre class="lyric text-white">${lyrics}</pre>`;
});
result.innerHTML= '';
}
// search by song or artist
function searchSongs(term){
fetch(`${api}/suggest/${term}`)
.then(res => res.json())
.then (showData);
};
// search result
function showData (data) {
result.innerHTML = `<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9"> ${data.data.map(song => `<h3 class="lyrics-name">${song.title}</h3>
<p class="author lead">${song.type} by <span>${song.artist.name}</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button onclick="getLyrics('${song.artist.name}','${song.title}')" class="btn btn-success">Get Lyrics</button>
</div>
</div>`)};
`;
};
//event listeners
search.addEventListener('click', function searchResult (){
const inputText = text.value.trim();
if (!inputText){
alert('this is not a song or artist')
}else {
searchSongs(inputText);
}
});
body{
background-color: #13141b;
color: #ffffff;
background-image: url(images/bg-image.png);
background-repeat: no-repeat;
background-size: 100%;
background-position: top;
}
.form-control{
background-color:rgba(255, 255, 255, 0.2);
padding: 22px;
border: none;
border-radius: 25px;
}
.btn{
border-radius: 1.5rem;
padding: 9px 20px;
}
.btn-privious{
background: rgba(255, 255, 255, 0.2);
color: #ffffff;
}
.navbar-toggler {
border: none;
}
.search-box{
position: relative;
}
.search-btn {
position: absolute;
top: 0;
right: 0;
height: 100%;
}
.single-result{
background: rgba(255, 255, 255, 0.2);
border-radius: 15px;
}
<!doctype html>
<html lang="en">
<head>
<title>Hard Rock Solution - Song Lyric App</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- Custom css -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-dark my-3">
<a class="navbar-brand" href="#">
<img src="images/logo.png" alt="Hard Rock Solution">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<img src="images/toggler-icon.svg" alt="">
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdownId">
<a class="dropdown-item" href="#">Action 1</a>
<a class="dropdown-item" href="#">Action 2</a>
</div>
</li>
</ul>
</div>
</nav>
<main class="content-area">
<div class="search-bar col-md-6 mx-auto">
<h1 class="text-center">Lyrics Search</h1>
<div class="search-box my-5">
<input id="text" type="text" class="form-control" placeholder="Enter your artist song name">
<button id="search" class="btn btn-success search-btn">Search</button>
</div>
</div>
<!-- === Simple results === -->
<div class="d-flex justify-content-center">
<div id="result" class="">
</div>
<!-- Single Lyrics -->
<div id="getLyric" id="artistTitle" class="single-lyrics text-center">
</div>
</div>
</main>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Custom Script Here -->
<script src ="javascrpt.js"> </script>
</body>
</html>
try to use autocomplete="off" like
<input type="text" name="foo" autocomplete="off" />
Every time, search is clicked, the lyrics container should be emtpied:
document.querySelector("#getLyric").childNodes.forEach(el => el.remove())
to fix the issue, add this to your script:
document.querySelector("#search").addEventListener('click', function () {
document.querySelector("#getLyric").innerHTML = '';
})

Want to add search result when search button is clicked

I am beginner in JavaScript. I am creating a project. Now i want to add a function when search button is clicked then search result display. However with the help of lecture i figure out how to filter when user is typing. But i want to add after typing in Search Bar when user click on search button then it also give the search result on same page same as it giving while typing.
showNotes();
// If user adds a note, add it to the localStorage
let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function (e) {
let addTxt = document.getElementById("addTxt");
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value);
localStorage.setItem("notes", JSON.stringify(notesObj));
addTxt.value = "";
//console.log(notes)
showNotes();
});
// Function to show elements from localStorage
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
let html = "";
notesObj.forEach(function (element, index) {
html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Note ${index + 1}</h5>
<p class="card-text"> ${element}</p>
<button id="${index}"onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</button>
</div>
</div>`;
});
let notesElem = document.getElementById("notes");
if (notesObj.length != 0) {
notesElem.innerHTML = html;
} else {
notesElem.innerHTML = `Nothing to show`;
}
}
// function to delete a note
function deleteNote(index) {
let notes = localStorage.getItem("notes");
notesObj.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
// search code
let search = document.getElementById('searchTxt');
search.addEventListener("input", function(){
let inputVal = search.value.toLowerCase();
// console.log('Input event fired!', inputVal);
let noteCards = document.getElementsByClassName('noteCard');
Array.from(noteCards).forEach(function(element){
let cardTxt = element.getElementsByTagName("p")[0].innerText;
if(cardTxt.includes(inputVal)){
element.style.display = "block";
}
else{
element.style.display = "none";
}
// console.log(cardTxt);
})
})
<!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">
<title>Notes App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Magic Notes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" onclick="btnSearch()">Search</button>
</form>
</div>
</nav>
<div class="container my-3">
<h1>Welcome To Magic Notes</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Add a note</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3"></textarea>
</div>
<button class="btn btn-primary" id="addBtn">Add Note</button>
</div>
</div>
<hr>
<h1>Your Notes</h1>
<hr>
<div id="notes" class="row container-fluid"> </div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>

How to prevent jquery submit button from refreshing the HTML page?

I have a login page where the user enters his username and password, when he submits this form the data is sent to php file for verifying the password.
For the first time when the user enters data (I entered wrong details) the page shows "Invalid password...please try again".
The second time when the user enters data (again I enter wrong details) the page just reloads. I am not able to understand why this is happening.
For more better understanding I have added a google drive link to a video showing the issue.
Link:Link to the video
The html code:
<!DOCTYPE html>
<html lang="en" xmlns:justify-content="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1 ">
<title>RVPS Elections</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark padding ">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">
<img src="assets/rv.png">
RV PUBLIC SCHOOL
</a>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="admin.html">Admin Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Contact Us</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<p align="center" class="lead">Get administrator access by entering correct details</p>
</div>
<div class="container-fluid padding mt-1 " style="align-items: center; justify-content:center; display:flex ;" >
<div class="row padding">
<div class="card border-dark" >
<div class="card-header" align="center">
<img src="assets/rv.png">
<h5>Admin Sign In</h5>
</div>
<div class="card-body" id="admin-signin-card">
<form id="admin-signin">
<div class="form-group">
<label>Username</label>
<input id="admin_username" type="text" class="form-control input-lg" placeholder="Enter your username" required>
</div>
<div class="form-group">
<label>Password</label>
<input id="admin_password" type="password" class="form-control input-lg" placeholder="Enter your Password" required>
</div>
<div class="form-group">
Forgot Password?
</div>
<div class="form-group" >
<input id="submit_button" type="submit" name="Sign In" value="Sign In" class="btn btn-success input-lg">
</div>
</form>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid padding">
<h1 align="center">About Us</h1>
<p align="center">I am Goutam B Seervi. A student of RVPS for the year 2015-18</p>
<h2 align="center">Contact me</h2>
<p align="center">Phone nnumber : 7019271367</p>
<p align="center">Email id : goutambseervi#gmail.com</p>
</div>
</footer>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="js/admin_login_script.js"></script>
</html>
The javascript part:
$(document).ready(function () {
$("#admin-signin").submit(function (e) {
e.preventDefault();
let admin_username = $("#admin_username").val();
let admin_password = $("#admin_password").val();
$.ajax({
url: 'php_admin_login.php',
data: {
admin_username: admin_username,
admin_password: admin_password
},
type: "POST",
dataType: "json",
success: function (response) {
if (response === "OK") {
window.open("admin.html", "_self");
}
else {
document.getElementById('admin-signin-card').innerHTML += '<div class="alert alert-danger"><h5>Error occured...Please try again</h5></div>';
console.log("error shown");
}
}
});
});
});
I'm sure there is no problem with the php code so I'm not pasting here just to make the question more clearer.
If you need the whole code of the project you can get it here:Github link to the project
else {
document.getElementById('admin-signin-card').innerHTML += '<div class="alert …>';
Adding to an element’s .innerHTML replaces the whole content of the element; even the stuff that was already there will first be removed, and then re-created.
So your form itself is replaced with a new form, and therefor you completely lose your submit event handler you had attached to it as well.
Your attempts at preventing the default event action fail, because you handler function simply doesn’t get called any more at all, and just a normal form submit is performed now, which of course reloads the page.
You need to either add your event handler again after you replaced the parent container’s innerHTML - or use event delegation to begin with.
Try to use this. Hope it will help
$("form").submit(function(e){
e.preventDefault();
});
Kindly let me know if it does not work.
Try return false at the end of your $("#admin-signin").submit function instead of the preventDefault()
This is happening due to how you handle errors. By using document.getElementById('admin-signin-card').innerHTML += ... you are effectively reloading your form meaning that you lose the event listener. You can either adjust how you display the error or adjust the event listener.
I would recommend changing how you display the error.
I have removed the request in the example below but it's the same idea:
$(document).ready(function () {
$("#admin-signin").submit(function (e) {
e.preventDefault();
let admin_username = $("#admin_username").val();
let admin_password = $("#admin_password").val();
let response = "no";
if (response === "OK") {
window.open("admin.html", "_self");
} else {
document.getElementById('admin-signin-card-error').innerHTML ='<div class="alert alert-danger"><h5>Error occured...Please try again</h5></div>';
console.log("error shown");
}
});
});
<!DOCTYPE html>
<html lang="en" xmlns:justify-content="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1 ">
<title>RVPS Elections</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark padding ">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">
<img src="assets/rv.png"> RV PUBLIC SCHOOL
</a>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="admin.html">Admin Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Contact Us</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<p align="center" class="lead">Get administrator access by entering correct details</p>
</div>
<div class="container-fluid padding mt-1 " style="align-items: center; justify-content:center; display:flex ;">
<div class="row padding">
<div class="card border-dark">
<div class="card-header" align="center">
<img src="assets/rv.png">
<h5>Admin Sign In</h5>
</div>
<div class="card-body" id="admin-signin-card">
<form id="admin-signin">
<div class="form-group">
<label>Username</label>
<input id="admin_username" type="text" class="form-control input-lg" placeholder="Enter your username" required>
</div>
<div class="form-group">
<label>Password</label>
<input id="admin_password" type="password" class="form-control input-lg" placeholder="Enter your Password" required>
</div>
<div class="form-group">
Forgot Password?
</div>
<div class="form-group">
<input id="submit_button" type="submit" name="Sign In" value="Sign In" class="btn btn-success input-lg">
</div>
</form>
<div id="admin-signin-card-error"></div>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid padding">
<h1 align="center">About Us</h1>
<p align="center">I am Goutam B Seervi. A student of RVPS for the year 2015-18</p>
<h2 align="center">Contact me</h2>
<p align="center">Phone nnumber : 7019271367</p>
<p align="center">Email id : goutambseervi#gmail.com</p>
</div>
</footer>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
</html>
like #CBroe mentioned, the problem is caused by innerHTML.
i moved the content of innerHTML to the form, and give it display none, when there an error i show the error with .show()
i changed the ajax url and data Type for testing purpose.
$(document).ready(function () {
$("#admin-signin").on('submit', function (event) {
event.preventDefault();
let admin_username = $("#admin_username").val();
let admin_password = $("#admin_password").val();
$.ajax({
url: 'https://jsonp.afeld.me/?url=https://jsonview.com/example.json',
type: "POST",
dataType: "jsonp",
data: {
admin_username: admin_username,
admin_password: admin_password
},
success: function (response) {
if (response === "OK") {
window.open("admin.html", "_self");
} else {
$('.alert.alert-danger').show();
console.log("error shown");
}
}
});
});
});
<!DOCTYPE html>
<html lang="en" xmlns:justify-content="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1 ">
<title>RVPS Elections</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid padding mt-1 " style="align-items: center; justify-content:center; display:flex ;" >
<div class="row padding">
<div class="card border-dark" >
<div class="card-header" align="center">
<h5>Admin Sign In</h5>
</div>
<div class="card-body" id="admin-signin-card">
<form id="admin-signin">
<div class="form-group">
<label>Username</label>
<input id="admin_username" type="text" class="form-control input-lg" placeholder="Enter your username" required>
</div>
<div class="form-group">
<label>Password</label>
<input id="admin_password" type="password" class="form-control input-lg" placeholder="Enter your Password" required>
</div>
<div class="form-group">
Forgot Password?
</div>
<div class="form-group" >
<input id="submit_button" type="submit" name="Sign In" value="Sign In" class="btn btn-success input-lg">
</div>
<div class="alert alert-danger" style="display: none;"><h5>Error occured...Please try again</h5></div>
</form>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
</body>
</html>

Categories

Resources