Click on the button and show Alert - javascript

The following code shows an alert box:
I want each box to be displayed by clicking on its own button
html
<button class="btn-alert btn-success" type="submit">delete</button>
<button class="btn-alert btn-success" type="submit">delete</button>
<button class="btn-alert btn-success" type="submit">delete</button>
<div class="alert-s col-4"></div>
<div class="alert-s col-4"></div>
<div class="alert-s col-4"></div>
<script>
const targetDiv = document.getElementById("alert");
const btn = document.getElementById("toggle");
function clickfn() {
for(let i = 0; i < targetDiv.length; i++) {
if (targetDiv.style.display = "none") {
targetDiv.style.display = "block";
} else {
targetDiv.style.display = "none";
}
}
};
</script>
can anyone help me to do so?

You can add a class to all your buttons, lets say toggle, then use javascript to call your function like:
var btns = document.getElementsByClassName('toggles');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
alert("Finaly!");
}
}

you don't need the for loop as getElementById returns a single element.
If you want to show alert on both button click and don't want to write two separate codes give them a similar class name and query them that way using document.querySelectorAll(a dot class name in quotes).
<button class="btn">Button one</button>
<button class="btn">Button two</button>
<script>
const btns = document.querySelectorAll(".btn");
for (let i = 0; i < btns.length; i++) {
btns[i].onclick = () => {
alert(`button ${i + 1} was clicked`);
};
}
</script>

Related

How to keep css style of element after reloading the web page in JS?

For example, I have some items whose status is completed and they have class completed
<body onload="loadItem()">
<ol class="list-group">
<li class="list-group-item completed" id="item-1">Text1</li>
<li class="list-group-item completed" id="item-2">Text2</li>
</ol>
</body>
Also, there are two buttons
<button type="button" onclick="showItem();" class="btn btn-outline-primary">Show completed</button>
<button type="button" onclick="hideItem();" class="btn btn-outline-primary">Hide completed</button>
And JavaScript functions
function hideItem() {
var targList = document.getElementsByClassName("completed");
var hidden_ids = []
for (var x = 0; x < targList.length; x++) {
targList[x].setAttribute('style', 'display: none !important');
hidden_ids.push(targList[x].id)
}
localStorage.setItem("autosave", JSON.stringify(hidden_ids));
}
function loadItem() {
var hidden_ids = JSON.parse(localStorage.getItem("autosave") || '[]');
for (var x = 0; x < hidden_ids.length; x++) {
document.getElementById(hidden_ids[x]).setAttribute('style', 'display: none !important');
}
}
function showItem() {
var targList = document.getElementsByClassName("completed");
var hidden_ids = []
for (var x = 0; x < targList.length; x++) {
targList[x].setAttribute('style', 'display: flex');
hidden_ids.push(targList[x].id)
}
localStorage.setItem("autosave", JSON.stringify(hidden_ids));
}
But, it does not work. On page reload it only hides completed items. However, I want it to be shown as default and if I press Hide button, it should be hidden even after page reload
Instead of storing id's, you might be use this solution maybe? If I understand your question correctly, it might be help.
function loadItem() {
if (localStorage.getItem('hide')) {
hideItem()
}
}
function showItem() {
localStorage.removeItem('hide')
document.querySelectorAll('.completed').forEach(li => li.style.display = 'list-item')
}
function hideItem() {
localStorage.setItem('hide', true)
document.querySelectorAll('.completed').forEach(li => li.style.display = 'none')
}

Radio Button On Bootstrap 5 Not Working With this JS Check

This The code i Make it In JS:
I need to head and show some element in change radio button event;
let radioChange = document.getElementsByName("pain-location");
let headPain = document.getElementById("headPain");
let shoulderPain = document.getElementById("shoulderPain");
let backPain = document.getElementById("backPain");
let listInner = document.getElementsByClassName("list-inner");
radioChange[0].addEventListener('click', (e) => {
if(document.getElementById('painOption1').checked) {
for (let i=0;i<listInner.length;i+=1){
listInner[i].style.display = 'none';
}
headPain.style.display = "block";
} else if(document.getElementById('painOption2').checked) {
for (let i=0;i<listInner.length;i+=1){
listInner[i].style.display = 'none';
}
shoulderPain.style.display = "block";
} else if(document.getElementById('painOption3').checked) {
for (let i=0;i<listInner.length;i+=1){
listInner[i].style.display = 'none';
}
backPain.style.display = "block";
}
});
This Is the HTML:
<div class="btn-group man-points">
<div class="ptn-check-point" id="optionBtn1">
<input type="radio" class="btn-check" name="pain-location" id="painOption1" required>
<label class="btn btn-secondary" for="painOption1"></label>
</div>
<div class="ptn-check-point" id="optionBtn2">
<input type="radio" class="btn-check" name="pain-location" id="painOption2" checked required>
<label class="btn btn-secondary" for="painOption2"></label>
</div>
<div class="ptn-check-point" id="optionBtn3">
<input type="radio" class="btn-check" name="pain-location" id="painOption3" required>
<label class="btn btn-secondary" for="painOption3"></label>
</div>
</div>
<div class="list-inner" id="headPain">
<h5>Head</h5>
</div>
<div class="list-inner" id="shoulderPain">
<h5>Shoulder</h5>
</div>
<div class="list-inner" id="backPain">
<h5>Shoulder</h5>
</div>
I Used Bootstrap 5
This The code i Make it In JS: I need to head and show some element in change radio button event;
Check this, you are adding event listener only for the first one, here i have added event listener to all radio fields by fetching all and looping through all.
let headPain = document.getElementById("headPain");
let shoulderPain = document.getElementById("shoulderPain");
let backPain = document.getElementById("backPain");
let listInner = document.getElementsByClassName("list-inner");
document.querySelectorAll('input[name="pain-location"]').forEach(element => {
element.addEventListener('click', (e) => {
if (document.getElementById('painOption1').checked) {
for (let i = 0; i < listInner.length; i += 1) {
listInner[i].style.display = 'none';
}
headPain.style.display = "block";
} else if (document.getElementById('painOption2').checked) {
for (let i = 0; i < listInner.length; i += 1) {
listInner[i].style.display = 'none';
}
shoulderPain.style.display = "block";
} else if (document.getElementById('painOption3').checked) {
for (let i = 0; i < listInner.length; i += 1) {
listInner[i].style.display = 'none';
}
backPain.style.display = "block";
}
});
})
ref: How to use on addEventListener on radio button in Plain Javascript?
Credits: https://stackoverflow.com/users/5947043/adyson

Click all buttons with same class

i've been trying to click all buttons with the same class class on a page after 10 seconds .This is in the google console.
var myVar = setInterval(myTimer, 10000);
function myTimer() {
var items = document.getElementsByClassName('button-play');
for (var i = 0; i < items.length; i++)
{
items[i].click();
}
}
problem is that it only clicks on the first 2 buttons then it goes back to the first in a loop
it skips the rest of the buttons on the page
You can share your HTML code so that we can check if there is any mistakes in your HTML or JavaScript code.
You can try your code in below format. This is working for me:
<html>
<body>
<button type="button" class="button-play" onclick="buttonClicked('Play1');"> Play1 </button>
<button type="button" class="button-play" onclick="buttonClicked('Play2');"> Play2 </button>
<button type="button" class="button-play" onclick="buttonClicked('Play3');"> Play3 </button>
</body>
<script>
var myVar = setInterval(myTimer, 10000);
function myTimer() {
console.log(new Date());
var items = document.getElementsByClassName('button-play');
for (var i = 0; i < items.length; i++) {
items[i].click();
}
}
function buttonClicked(text) {
console.log(text);
}
</script>
</html>
Output:

use location.hash to keep page status in javascript

I am doing a practice that use location.hash to keep page's state, what i have done using the below code is
1.click any button, the button's innerHTML will be written into the div#cont
2.refresh the page, it keeps the changes in the div#cont
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
And what i want to achieve next is add three other buttons(D,E,F) and a new div, when clicking one of the D\E\F, the innerHTMl will written into the new div.
The final goal is
click one of the A\B\C, the value will be written into 'contABC'
click one of the D\E\F, the value will be written into 'contDEF'
keep the changes when the page refresh
because this time it has to record two value, and i have no idea how to use hash to do that, anyone can help? Thanks in advance!
This is HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
Try by structuring the way you store the hash value , like using a separator -
<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash && location.hash.slice(1);
return hashValue && hashValue.split('-');
}
function draw() {
var cont = getHash();
if (cont && cont.length>0) {
document.getElementById('contABC').innerHTML = cont[0];
document.getElementById('contDEF').innerHTML = cont[1];
}
}
btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
var cont = getHash() || [];
if(btns[this.index].dataset.attr=='ABC'){
location.hash = btns[this.index].innerHTML + seperator + cont[1];
}else{
location.hash = cont[0] + seperator + btns[this.index].innerHTML ;
}
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>

Local Storage remove Item and remove list

I am at the end of my Project. I have problem with add favorites and to remove item from local storage. It works to delete it from html but when you refresh the page, items are again here. Also remove whole favorites its not working. I hope that someone see my mistake
I try to remove whole list with function but its also not working.
<body>
<main>
<h1>Your Favourite Recipes</h1>
<p>These are your favourite recipes that we have saved for you.</p>
<button id="probam" type="button"
name="button" onclick="deleteListe()">brisi</button>
<p id="fav"></p>
<script>
let list = localStorage.getItem('favorites');
list = list ? list.split(',') : [];
var ll = [];
ll = list;
var output = document.createElement('ul');
output.setAttribute('id', 'list')
for (let i = 0; i < ll.length; i++) {
var it = document.createElement('li');
var bt = document.createElement('button');
bt.innerHTML = ('Delete');
bt.setAttribute('class', 'delete')
it.appendChild(document.createTextNode(ll[i]));
it.appendChild(bt);
output.appendChild(it);
}
document.getElementById('fav').appendChild(output);
var del = document.getElementsByClassName('delete');
for (let j = 0; j < del.length; j++) {
del[j].addEventListener('click', function() {
// console.log((del[j].parentNode).parentNode);
(del[j].parentNode).parentNode.removeChild(del[j].parentNode);
})
}
function deleteListe() {
localStorage.removeItem("favorites");
}
</script>
<button type="button" name="button"></button>
<a href="index.html" class='vido'>Home</a>
</main>
</body>
I little change your code, and i added for all button required functions
<h1>Your Favourite Recipes</h1>
<p>These are your favourite recipes that we have saved for you.</p>
<button id="probam" type="button" name="button" onclick="deleteListe()">brisi</button>
<p id="fav"></p>
<script>
function deleteListe() {
localStorage.removeItem("favorites");
}
function deleteElement(element) {
const newFavorites = (localStorage.getItem('favorites')||"").replace(element,"");
localStorage.setItem("favorites",newFavorites.split(",").filter(Boolean).join(","));
setTimeout(()=>{
localStorage.getItem('favorites')
location.reload();
},10);
}
let list = (localStorage.getItem('favorites')||"").split(",").filter(Boolean);
var output = document.createElement('ul');
output.setAttribute('id', 'list')
list.forEach((el)=>{
var it = document.createElement('li');
var bt = document.createElement('button');
bt.innerHTML = ('Delete');
bt.setAttribute('class', 'delete');
bt.setAttribute('title', el);
it.appendChild(document.createTextNode(el));
it.appendChild(bt);
output.appendChild(it);
});
document.getElementById('fav').appendChild(output);
var del = document.getElementsByClassName('delete');
for (let j = 0; j < del.length; j++) {
del[j].addEventListener('click', function() {
deleteElement(this.getAttribute('title'));
(this.parentNode).parentNode.removeChild(this.parentNode);
})
}
</script>
<button type="button" name="button"></button>
<a href="index.html" class='vido'>Home</a>

Categories

Resources