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>
Related
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>
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"
});
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 = [];
}
Here error is coming is can't access a property of undefined, In this.dataLog when I'm trying to push something in it. Please resolve the same. It is showing this.dataLog array as undefined.Here error is coming is can't access a property of undefined, In this.dataLog when I'm trying to push something in it. Please resolve the same. It is showing this.dataLog array as undefined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9147344c85.js" crossorigin="anonymous" defer></script>
<!-- <link href="https://unpkg.com/tailwindcss#^1.0/dist/tailwind.min.css" rel="stylesheet"> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
<script src="index.js" type="text/javascript" defer></script>
<title>Document</title>
</head>
<body>
<div class="alert alert-success height" role="alert">
<img src="https://source.unsplash.com/random/70x100" id="main-img" class="">
<span>NatureFresh.com</span>
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a id="login-link" class="navbar-brand" href="#">Login</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>
<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="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="dropdown">
<a class="btn btn-secondary dropdown-toggle side-anchor" href="#" role="button" id="dropdownMenuLink"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Important links
</a>
<div id="login-back">
<form id="login">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" aria-describedby="basic-addon1" placeholder="Username">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control"placeholder="Password" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="alert alert-success sucessful" role="alert">
<h4 class="alert-heading">Welcome Back!</h4>
<hr>
<p></p>
</div>
<div class="dropdown-menu inside-anchor" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="https://www.facebook.com/">Facebook</a>
<a class="dropdown-item" href="#">Twitter</a>
<a class="dropdown-item" href="#">Gmail</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
</body>
</html>
class LoginDisplay {
constructor() {
this.dataLog=[];
}
render() {
// let loginLink = document.querySelector("#login-link");
let loginBack = document.querySelector("#login-back");
let loginForm = document.querySelector("#login");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector("input[type=\"email\"]");
let inputPassword = document.querySelector("input[type=\"password\"]");
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
inputName.value = "";
inputEmail = "";
inputPassword = "";
}
validation() {
let loginForm = document.querySelector("#login");
let loginBack = document.querySelector("#login-back");
let sucessAlert = document.querySelector("div[class=\"alert alert-success sucessful\"]");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector("input[type=\"email\"]");
let inputPassword = document.querySelector("input[type=\"password\"]");
let patt = /^[A-Za-z0-9]{2,}#[a-zA-Z0-9]{1,10}.com$/;
let para = sucessAlert.querySelector("p");
if (patt.test(inputEmail.value) && inputPassword.value === "dhawan") {
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
para.innerHTML = `<h4>Namste! ${inputName.value} <i class="fas fa-check"></i></h4>`;
inputName.value = "";
inputEmail = "";
inputPassword = "";
sucessAlert.classList.toggle("visible");
debugger;
this.dataLog.push(para);
}
// else{
// para.innerHTML=`<h4>`
// }
}
ve(){
console.log(this.dataLog.push("Sudhir"));
}
}
let login = new LoginDisplay();
let loginLink = document.querySelector("#login-link");
let btn= document.querySelectorAll("button[type=\"submit\"]")[1];
loginLink.addEventListener("click", login.render);
btn.addEventListener("click",login.validation)
This is the solution to your problem, but I think it has many ways to do it.
class LoginDisplay {
constructor() {
this.dataLog = [];
}
render() {
// let loginLink = document.querySelector("#login-link");
let loginBack = document.querySelector("#login-back");
let loginForm = document.querySelector("#login");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector('input[type="email"]');
let inputPassword = document.querySelector('input[type="password"]');
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
inputName.value = "";
inputEmail = "";
inputPassword = "";
}
validation() {
let loginForm = document.querySelector("#login");
let loginBack = document.querySelector("#login-back");
let sucessAlert = document.querySelector(
'div[class="alert alert-success sucessful"]'
);
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector('input[type="email"]');
let inputPassword = document.querySelector('input[type="password"]');
let patt = /^[A-Za-z0-9]{2,}#[a-zA-Z0-9]{1,10}.com$/;
let para = sucessAlert.querySelector("p");
let a = patt.test(inputEmail.value) && inputPassword.value === "dhawan";
console.log(!a);
if (!a) {
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
para.innerHTML = `<h4>Namste! ${inputName.value} <i class="fas fa-check"></i></h4>`;
inputName.value = "";
inputEmail = "";
inputPassword = "";
sucessAlert.classList.toggle("visible");
//debugger;
return para;
}
// else{
// para.innerHTML=`<h4>`
// }
}
ve() {
console.log(this.dataLog.push("Sudhir"));
}
}
let login = new LoginDisplay();
let loginLink = document.querySelector("#login-link");
let btn = document.querySelectorAll('button[type="submit"]')[1];
loginLink.addEventListener("click", login.render);
btn.addEventListener("click", () => {
if (login.validation) {
let result = login.validation();
login.dataLog.push(result);
console.log(login.dataLog); // Here you have your element tag HTML in your Array!
}
});
I need a button that opens up a module in bootstrap when condition is true
User inputs his btc address and than i check if its a valid btc address- if it is valid an modal should open and display the user a receiving address.
When the user input =! a btc address the modal should stay closed.
The code for checking the Btc address works- all i need is to hook up the result to my button.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>BItmixxer</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style media="screen">
hr.style1{
border-top: 1px solid #8c8b8b;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Navbar</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron jumbotron-fluid" style="text-align:center" >
<div class="container">
<h1>Crypto BItmixxer</h1>
<p>some more Text about rypto mixxer</p>
</div>
</div>
<div class="container" style="text-align:center" >
<h1>BTC MIxxer</h1>
<p>Choose COins to mix:</p> <button type="button" class="btn btn-outline-primary">Bitcoin</button>
<button type="button" class="btn btn-outline-success">Ethereum</button>
<br>
<br>
<br>
<div class="form-group" id="elMessage" class="msg">
<input type="text" class="form-control" id="inpAddress" value="">
</div>
<button type="button" class="btn btn-primary" id="btnValidate" data-toggle="modal" data-target="#myModal">Next</button>
<script>
var normalize = (s) => {
let x = String(s) || '';
return x.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
};
var check = (s) => {
if (s.length < 26 || s.length > 35) {
return false;
}
let re = /^[A-Z0-9]+$/i;
if (!re.test(s)) {
return false;
}
return true;
};
var getEl = (id) => {
return document.getElementById(id) || null;
};
var elMessage = getEl('elMessage');
var inpAddress = getEl('inpAddress');
var btnValidate = getEl('btnValidate');
var lnkClear = getEl('lnkClear');
var setMessage = (txt = '', clss = 'msg') => {
elMessage.className = clss;
elMessage.innerHTML = txt;
};
var validate = (s) => {
let className = 'msg fail';
let textMessage = 'Invalid bitcoin address';
if (!s) {
textMessage = 'Please enter a valid address';
}
let re = check(s);
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
}
setMessage(textMessage, className);
return re;
};
btnValidate.onclick = () => {
let v = normalize(inpAddress.value);
let result = validate(v);
if (result) {
inpAddress.value = v;
}
};
lnkClear.onclick = () => {
inpAddress.value = '';
inpAddress.focus();
setMessage('Enter any text and press "Validate"');
};
</script>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h3>Please send your BTC(min0.5) to</h3>
<p id ="btc-house" style="color:blue;"></p>
<script>
var myArray = ['1QFsuDg4HyCJZFBfC2ivxHCK2CX2i9YvWN', ' 1EhfSjMuyAyrpRRGf5sSCU3YDbVAqjJNxH', '1N2e39vyTrk6HtvZPqWPrHfHKBzsnQNN4V','1GVSGZxwU69fN5oPprSxXRnjsZPvo8bGw3'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("btc-house").innerHTML = rand;
</script>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
The Bootstrap modal can be opened using JS (https://getbootstrap.com/docs/4.0/components/modal/#via-javascript)
For that to work you have to remove the data-attributes from your button, and place the opening code in your JavaScript.
Note: I had to modify your code a bit, so it worked error-free as a snippet.
var normalize = (s) => {
let x = String(s) || '';
return x.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
};
var check = (s) => {
if (s.length < 26 || s.length > 35) {
return false;
}
let re = /^[A-Z0-9]+$/i;
if (!re.test(s)) {
return false;
}
return true;
};
var getEl = (id) => {
return document.getElementById(id) || null;
};
var elMessage = getEl('elMessage');
var inpAddress = getEl('inpAddress');
var btnValidate = getEl('btnValidate');
var lnkClear = getEl('lnkClear');
var setMessage = (txt = '', clss = 'msg') => {
elMessage.className = clss;
elMessage.innerHTML = txt;
};
var validate = (s) => {
let className = 'msg fail';
let textMessage = 'Invalid bitcoin address';
if (!s) {
textMessage = 'Please enter a valid address';
}
let re = check(s);
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
}
setMessage(textMessage, className);
return re;
};
btnValidate.onclick = () => {
let v = normalize(inpAddress.value);
let result = validate(v);
if (result) {
inpAddress.value = v;
// You have the modal with open it with JS
$('#myModal').modal('show')
}
};
/*lnkClear.onclick = () => {
inpAddress.value = '';
inpAddress.focus();
setMessage('Enter any text and press "Validate"');
};*/
var myArray = ['1QFsuDg4HyCJZFBfC2ivxHCK2CX2i9YvWN', ' 1EhfSjMuyAyrpRRGf5sSCU3YDbVAqjJNxH', '1N2e39vyTrk6HtvZPqWPrHfHKBzsnQNN4V', '1GVSGZxwU69fN5oPprSxXRnjsZPvo8bGw3'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("btc-house").innerHTML = rand;
hr.style1 {
border-top: 1px solid #8c8b8b;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Navbar</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron jumbotron-fluid" style="text-align:center">
<div class="container">
<h1>Crypto BItmixxer</h1>
<p>some more Text about rypto mixxer</p>
</div>
</div>
<div class="container" style="text-align:center">
<h1>BTC MIxxer</h1>
<p>Choose COins to mix:</p> <button type="button" class="btn btn-outline-primary">Bitcoin</button>
<button type="button" class="btn btn-outline-success">Ethereum</button>
<br>
<br>
<br>
<div class="form-group" id="elMessage" class="msg">
<input type="text" class="form-control" id="inpAddress" value="">
</div>
<button type="button" class="btn btn-primary" id="btnValidate">Next</button>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h3>Please send your BTC(min0.5) to</h3>
<p id="btc-house" style="color:blue;"></p>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>