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/
Related
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.
so I want to make an animation whenever you click a button, and in js I would probably do it something like that:
var x = document.GetElementById("inputBox");
function changeToRegister(){
x.style.justify-content: flex-start;
}
but when I try something like that in react
const changeToRegister = () => {
var x = document.getElementsById("inputs");
x.style.justify-content: flex-start;
}
it just doesn't work, is there anyway to do what I did in the first code section in react? the function will be called after pressing a button
<button type="button" class="toggle-btn" onClick={changeToRegister}>Register</button>
It is not a good practice to var x = document.GetElementById("inputBox"); in react
Instead you can try this
const [justifyContentStart,setJustifyContentStart] = useState(false);
const changeToRegister = () => {
setJustifyContentStart(true)
}
<button
type="button"
class="toggle-btn"
onClick={changeToRegister}
style={ justifyContentStart ? { justifyContent:'flex-start'} : null }
>Register</button>
Use a state variable to decide whether to apply that particular style or not
Initially that state variable is set to false hence style is not applied
Once the user clicks on Button, The state variable will be set to true and the style you want can be applied
Currently I am getting a huge object when I'm logging x.
How to get the value from the event?
function IncrementOnClick() {
function increment(x) {
console.log(x);
}
return (
<div>
<button onClick={increment}>1</button>
</div>
);
}
It would seem you are using reactJs rather then pure JavaScript.
By calling onClick={increment} the parameter you pass to increment is an event. To get the target that you clicked on use x.target, and if you want the targets value x.target.value. for example:
const increment = ({ target }) => console.log(target.value);
return (
<div>
<button value="submit" onClick={increment}>
Manikanta
</button>
</div>
);
EDIT
Since you wish the get the inner text Manikanta rather then the actual value, use target.innerText. So in this case would be:
const increment = ({ target }) => console.log(target.innerText);
return (
<div>
<button onClick={increment}>Manikanta</button>
</div>
);
I didn't quite understand what you wanted to return but if I understood correctly this is the right code
function increment(x) {
console.log(x);
return x;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<div>
<button onClick="increment(20);">Manikanta</button>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I believe you are using React seeing your return statement and the curly braces JS blocks in the JSX. You can do something like the following:
import React, {useState} from "react";
function IncrementOnClick() {
// Setup the state to store the clicks
const [clicks, setClicks] = useState(0);
// You can learn more about hooks here:
// https://reactjs.org/docs/hooks-intro.html
function increment(e) {
// The argument `e` that you get to the function is the click
// event, which can be used to get a lot of information about
// the click like the coordinates of the click, button's information
// and a lot more other information.
// every time the button is clicked, you add 1 to the clicks.
setClicks((prevClicks) => prevClicks + 1);
}
return (
<div>
<button onClick={increment}>Clicks = {clicks}</button>
</div>
);
}
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);
}
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>