How to single select button using jquery? - javascript

How can I manipulate CSS and read text value and save it into variable when clicking on the button. when I click on the button using jquery how can I add a CSS to the button such as class="btn-n-active".
How to make sure that only one button is selected while switching on different buttons and that button should have active CSS
I was trying to just read the single value from the options, just a single selection.
<p>
<button onclick="myFunction()" class="btn-n">DOG</button>
<button onclick="myFunction()" class="btn-n">CAT</button>
<button onclick="myFunction()" class="btn-n">LION</button>
<button onclick="myFunction()" class="btn-n">PIG</button>
</p>
const myFunction = () => {
}
It's like a quiz system where I just want to read a single value. I am not able to apply the logic

There are a bunch of options to do this. Below you will see 3 of them.
The idea is to select all buttons and remove the active class and then add it to the button you clicked on.
My jquery is a bit rusty but I suggest you use just javaScript for such a simple request
const myFunction = (event) => {
const clickedElem = event.target
const allBtns = document.querySelectorAll('.btn-n')
allBtns.forEach(btn => btn.classList.remove("btn-n-active"))
clickedElem.classList.add("btn-n-active")
}
// option 2 without adding function in html
/* const allBtns = document.querySelectorAll('.btn-n')
allBtns.forEach(btn => btn.onclick = () => {
allBtns.forEach(btn => btn.classList.remove("btn-n-active"))
btn.classList.add("btn-n-active")
}) */
//option3 simple jQuery
/* const allBtns = $('.btn-n');
allBtns.click(function() {
$(this).addClass("btn-n-active")
allBtns.not(this).removeClass("btn-n-active")
}) */
const submit = () => {
const selectedText = document.querySelector(".btn-n-active") ? document.querySelector(".btn-n-active").innerText : 'Please select one'
console.log(selectedText)
}
.btn-n-active {
background: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<button onclick="myFunction(event)" class="btn-n">DOG</button>
<button onclick="myFunction(event)" class="btn-n">CAT</button>
<button onclick="myFunction(event)" class="btn-n">LION</button>
<button onclick="myFunction(event)" class="btn-n">PIG</button>
</p>
<button onclick="submit()">Click to see selected text</button>

You can find the selected answer button having the active class using the hasClass('btn-n-active')
$("button").click(function(){
$("button").removeClass("btn-n-active"); // Remove other active class
$(this).addClass("btn-n-active"); // Add active class to the clicked button
});
const myFunction = () => {
var selectedButtonText = $("button").hasClass("btn-n-active").html();
console.log("Selected answer: " + selectedButtonText);
}

Related

Mobile Friendly image Hotspot with clickable buttons

I am trying to use the mobile friendly hotpot code from codepen https://codepen.io/abcretrograde/pen/dKGOEL
When the user clicks on the hotspot is pops up with some text etc. I tried putting a button and a link in to popup but neither work.
In the JavaScript I have tried adding EventListeners to the buttons but they still wont fire when user clicks on them. anyone got any ideas?
in the javascript i have tried both the following, get no errors but doesn't do anything
<div class="lg-container">
<img id="skyemap" src="/assets/imgs/map.png" class="lg-image" alt="myMap" />
<div style="top: 70%; left: 50%;" class="lg-hotspot lg-hotspot--top-left">
<div class="lg-hotspot__button"></div>
<div class="lg-hotspot__label">
<h4>View More Details</h4>
</p>Click the button to view more information
<button class="btn btn-sm btn-success btnFP" id="btnFP">Visit Here</button>
</p>
</div>
</div>
<script>
const selectHotspot = (e) => {
const clickedHotspot = e.target.parentElement;
const container = clickedHotspot.parentElement;
const hotspots = container.querySelectorAll(".lg-hotspot");
hotspots.forEach(hotspot => {
if (hotspot === clickedHotspot) {
hotspot.classList.toggle("lg-hotspot--selected");
const childHP = hotspot.querySelector('.lg-hotspot__label');
const btn = childHP.querySelector('.btn');
childHP.addEventListener('click', ()=>{
alert('clicked');
});
} else {
hotspot.classList.remove("lg-hotspot--selected");
}
});
}
(() => {
const buttons = document.querySelectorAll(".lg-hotspot__button");
buttons.forEach(button => {
button.addEventListener("click", selectHotspot);
});
})();
const btnFP = document.getElementById('btnFP');
btnFP.addEventListener('click', ()=>{
alert('clicked');
});

How to remove duplicate instances of class

In javascript, I am trying to apply an 'active' class upon clicking a button. However, I would then like to remove the class from the button which previously had it. I'm not sure how to best go about this. I was considering something involving a second loop after the click, but that seems somewhat convoluted, and like there's probably a better way. Here's the code I have to add the class, but again, not sure how to best go about removing it from the button to which it was previously applied.
const giftcards = document.querySelectorAll('.giftcard');
for(let giftcard of giftcards){
giftcard.onclick = () => {
giftcard.classList.add('active');
}
}
If there is always at most one .giftcard with an active class you could query for that giftcard before setting active to the currently clicked one using document.querySelector('.giftcard.active') and utilize Optional chaining (?.) to remove the active class only if an element was found.
const giftcards = document.querySelectorAll('.giftcard');
for (let giftcard of giftcards) {
giftcard.onclick = () => {
document.querySelector('.giftcard.active')?.classList.remove('active');
giftcard.classList.add('active');
}
}
.active {
color: red;
}
<div class="giftcard">card 1</div>
<div class="giftcard">card 2</div>
<div>
<button class="giftcard">Button 1</button>
<button class="giftcard">Button 1</button>
<button class="giftcard">Button 1</button>
</div>
<script>
const giftcards = document.querySelectorAll(".giftcard");
giftcards.forEach((giftcard) => {
giftcard.addEventListener("click", () => {
giftcardClick(giftcard);
});
});
function giftcardClick(giftcard) {
giftcards.forEach((giftcard) => {
giftcard.classList.remove("active");
});
giftcard.classList.add("active");
}
</script>

I Want a Button that hide the div and restore it

I want to create a button that will hide each ticket and one general button that will restore them all.
this is the Code:
return (
<ul className="tickets">
{filteredTickets.map((ticket) => (
<li key={ticket.id} className="ticket">
<h5 className="headline">{ticket.headline}</h5>
<p className="text">{ticket.text}</p>
<footer>
<div className="data">
By {ticket.address} | {new Date(ticket.time).toLocaleString()}
</div>
</footer>
</li>
))}
</ul>
);
here is an example of what you want!
you have to replace myFunction() for your button and myDIV into your element that you want to hide it!
<button onclick="myFunction()">Click Me</button>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
for react =
const [visible, setVisible] = useState(true)
here is for button
<button onlick={() =>setVisible(!visible)}>hide/show
here is a demo in JS, modify to what you want exactly
<ul class="ticket">
<li>
<p>hey, I'm a P</p>
<div class="data">I'm a Div</div>
</li>
</ul>
.hide {display:none}
const generalBtn = document.getElementById(`btn`);
const divContainer = document.querySelector(`.ticket`);
const eachDiv = divContainer.getElementsByClassName(`data`);
generalBtn.addEventListener(`click`, () => {
[...eachDiv].forEach((div) => {
div.classList.toggle(`hide`);
});
});
There is a good solution in your case but as mentioned in the comments, it needs to manipulate the filteredTickets array.
You need to add a property/value to each item of filteredTickets to track or change their state. For example, it can be isVisible property which is a boolean with false or true value.
Now, isVisible value will determine the behavior. let's modify the ticket:
const handleHideTicket = (id) => {
// find selected ticket and ​change its visibility
​const updatedFilterdTickets = filteredTikcets.map(ticket => (ticket.id === id ? {...ticket, isVisible: false} : ticket))
// now the updatedFilterdTickets need to be set in your state or general state like redux or you need to send it to the server throw a API calling.
}
return (
​<ul className="tickets">
​{filteredTickets.filter(ticket => ticket.isVisible).map((ticket) => (
​<li key={ticket.id} className="ticket">
​<h5 className="headline">{ticket.headline}</h5>
​<p className="text">{ticket.text}</p>
​<footer>
​<div className="data">
​By {ticket.address} | {new Date(ticket.time).toLocaleString()}
​</div>
// add a button to control visibility of each ticket
​<button onClick={() => handleHideTicket (ticket.id)}> click to hid / show </button>
​</footer>
​</li>
​))}
​</ul>
);
Explanation:
a new button added to each ticket and pass the handleHideTicket handler to it. If the user clicks on this button, the handler finds that ticket and sets the isVisible property to the false.
On the other hand, we can remove the hidden tickets by applying a simple filter method before map method. so only visible tickets will be displayed.
Now, create a general button to show all the tickets. In this case, you need a handler function that sets all ticket's isVisible value to true
const handleShowAllTickets = () => {
const updatedFilteredTickets = filteredTickets.map(ticket => ({...ticket, isVisible: true}))
// now put the updatedFilteredTickets in your general store/post an API call/ update state
}
Note: as I mentioned in the code's comments, you need to update your filteredTickets array after changing via handlers to reflect the changes in your elements.

Reset html link attribute

I have the following line in my html
a link
Then I'm using the chrome dev console to change the attribute data-url to another link. Can I in some way afterwards reset this link to its default value? I've seen a reset() function but I guess it doesn't work for this problem.
Store in another attribute
const anc = document.getElementById("anc1");
anc.dataset.saveurl = anc.dataset.url;
anc.dataset.url="otherurl";
Click
result:
Click
Another perfect use case for WeakMaps! 🎉🎉🎉
const wm = new WeakMap()
document.querySelectorAll('button').forEach(el => {
wm.set(el, el.dataset.url)
delete el.dataset.url
el.onclick = () => {
console.log('html:', el.outerHTML, '\nweakmap:', wm.get(el))
}
})
<button data-url="img/1.jpg">Click</button>
<br>
<button data-url="img/2.jpg">Click</button>
<br>
<button data-url="img/3.jpg">Click</button>

Why doesnt my code for my calculator work?

I have some uncompleted code that's suposed to return a number for what ever button I click but instead it does nothing and the console doesnt throw an error so that i cant see what i did.
Ive done some spell checking and my code comes mainly form a youtube video.
const minus = document.querySelector('[data-delete]');
const current = document.querySelector('[data-input]');
const allClear = document.querySelector('[data-all-clear]');
const numberButtons = document.querySelectorAll('[data-number]')
const operation = document.querySelectorAll('[data-operation]')
const equals =document.querySelector('[data-equals]')
class Calc {
constructor(inputText){
this.inputText = current
this.clear()
}
clear(){
this.input=''
this.operation=undefined
}
delete(){
}
writeNumber(num){
this.input = num
}
operation(sign){
}
compute(){
}
updateDisplay(){
this.input.innerText = this.operation
}
}
const calculator = new Calc(current);
numberButtons.forEach(number=>{
equals.onClick('click',()=>{
calculator.appendNumber(equals.innerText)
calculator.updateDisplay()
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<link href="calc.css" rel="stylesheet">
<script src="calc.js"></script>
</head>
<body>
<div class="container-grid">
<div data-input class="input">3</div>
<button data-all-clear class="span-two">AC</button>
<button data-delete>DEL</button>
<button data-operation>/</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operation>*</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operation>+</button>
<button data-number>7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operation>-</button>
<button data-number>.</button>
<button data-number>0</button>
<button data-equals class = "span-two">=</button>
</div>
<script src="calc.js"></script>
</body>
</html>
I just want the buttons to display numbers
I am able to run your code after doing the below change,
wrap everything inside one method,
you are having an issue with the below click event,
Incorrect one,
equals.onClick('click',()=>{
calculator.appendNumber(equals.innerText)
calculator.updateDisplay()
})
If you dont want jQuery use javascript click event bind()
equals.addEventListener("click",()=>{
calculator.writeNumber(equals.innerText)
calculator.updateDisplay()
})
Refer the below updated your function
function Calci() {
let minus = document.querySelector('[data-delete]');
let current = document.querySelector('[data-input]');
let allClear = document.querySelector('[data-all-clear]');
let numberButtons = document.querySelectorAll('[data-number]')
let operation = document.querySelectorAll('[data-operation]')
let equals =document.querySelector('[data-equals]')
class Calc {
letructor(inputText){
this.inputText = current
this.clear()
}
clear(){
this.input=''
this.operation=undefined
}
delete(){ }
writeNumber(num){
this.input = num
}
operation(sign){
}
compute(){ }
updateDisplay(){
this.input.innerText = this.operation
}
}
let calculator = new Calc(current);
numberButtons.forEach(number=>{
equals.addEventListener("click",()=>{
calculator.writeNumber(equals.innerText)
calculator.updateDisplay()
})
})
}
Calci(); //call the method
JS Fiddle Answer : https://jsfiddle.net/xa14fbc0/
So I'm not quite sure what you're trying to achieve here but I'll point out a few things that might help.
Are you trying to make your element with data-equals show the number button you click on?
your function
numberButtons.forEach(number=>{
equals.onClick('click',()=>{
calculator.appendNumber(equals.innerHTML)
})
})
needs some work, you wouldn't use use onClick('click'... instead you would use addEventListener('click'... to attach a handler (using .click to attach an on click handler is jQuery and you do not have jQuery setup in your code - might be something to look at). Furthermore, you are attaching the on click to the equals element each time over and over again, not to your buttons. For that you would do number.addEventListener('click'... to attach a click handler to each of your buttons so an action takes place each time you click. You also are calling a method calculator.appendNumber but your calculator class doesn't have an appendNumber method in it.
What you are looking for is something along the lines of :
numberButtons.forEach(number=>{
number.addEventListener('click',()=>{
calculator.appendNumber(number.innerText)
calculator.updateDisplay()
})
})
you also want to add an appendNumber method to your Calc class or call a method that is available in your Calc class
You are also instantiating calculator with current which is a dom element, but your Calc class constructor is looking for inputText so what you want there is something like :
const calculator = new Calc(current.value)
in order to pass in the value of your input - keep in mind that constructors get instantiated with the value at the time of instantiation and will not change as you change your input value - you'd need to attach an on change handler to your input in order for your class instance to make a change when that input value changes
I've made a JS fiddle that changes the input to a number you click to get you started, based on your code : https://jsfiddle.net/xa14fbc0/

Categories