Unable to get button value into function - javascript

Working on TOD calculator project.
While I likely have other potential errors in my code, I am only seeking to understand getting the button number/value into the function.
I think I need to get the button value assigned so that the
xyz function can process it. Is it even necessary to add the value attribute to a CSS button in this instance?
<div class="row4">
<button class="btn" value="7">7</button>
<button class="btn" value="8">8</button>
<button class="btn" value="9">9</button>
<button class="btn" value="*">*</button>
</div>
let buttons = document.getElementsByClassName("btn");
for (let i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener("click", xyz);
function xyz(x) {
let nbr1 = "0";
let operator = "";
let nbr2 = "0";
const sum = maths(nbr1, operator, nbr2);
if (x == "=") button.value = sum;
if (x == "+" || "-" || "*" || "/") x = operator;
if (operator == null) x = nbr1;
else x = nbr2;
console.log(nbr1, operator, nbr2);
}
}
document.getElementsByClassName("btn").value causes an
uncaught typeError: buttons is undefined
Without .values the function runs without errors, but none
of the values get assigned.
I have tried:
getAttributes(‘value’) and get: "not a function" typeError.
a number of different iterations in the (xyz) of lines such as: x, buttons, buttons.value etc.

First of all, you are redefining the function in every iteration of the loop (not necessary and not optimal). Just define the function before you start the loop.
The event handler will be passed the event object as the parameter. The event.target points to the actual clicked-on element which may be a child of the button, while event.currentTarget will be the element the handler was assigned to (the button itself).
If you only have the button value nested inside it then you can use event.currentTarget.innerText instead of event.currentTarget.value to get the value attribute.
let buttons = document.getElementsByClassName("btn");
function xyz(event) {
const btnVal = event.currentTarget.innerText
console.log(btnVal);
}
for (let i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener("click", xyz);
}
<div class="row4">
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<button class="btn">*</button>
</div>

Related

hiding a button in html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I want to hide a button on the click of another button. So i checked some questions on stack overflow . I used display property and assigned it to hidden. And now I want to unhide it on the click of another button.
I want to increment variable "a" on the click of button1. and when the variable a is greater or equal to three i want to unhide 'button' (The button which has id #again) which is hidden. That means after clicking in button1 twice i want to unhide the button. But It is not working. No mater how many times i click in the button1, it is not working.I used display property and made it to hidden in the html file.
Could anybody say what i want to do here in order to unhide the button when clicked on the button1 twice.
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++;
}
if (a >= 3) {
button.style.display = "block";
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
<script src="practise.js"></script>
Your if block is calculated just once in the beginning when the browser parses through the js file. Instead, you want to check it every time button1 is clicked. Move it inside the event listener.
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++
if (a >= 3) {
button.style.display = "block";
}
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
spelling onclick
if needs to go inside the function
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++;
if (a >= 3) {
button.style.display = "block";
}
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
<script src="practise.js"></script>
Alternative using eventListener and hidden
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.addEventListener("click", () => {
a++;
button.hidden = a < 3
})
<button id="again" hidden>click me</button>
<button id="again1">here</button>
<script src="practise.js"></script>
Just put the if condition inside the onClick() function .
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++
if (a > 2) {
button.style.display = "block";
}
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
Try this simple:
var button = document.getElementById("again1")
let button1 = document.querySelector("#again");
count = 0;
button.onclick = function() {
count += 1;
if (count >= 3) {
button1.style.display = "block";
}
button.innerHTML = "Click me: " + count;
};
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
Here in the above responses 'display: hidden' means it will occupy the space in UI where as 'display: none' means it won't occupy the space. Now you can decide which one to use as well

Why is addEventListener increment code not working?

I am still learning and I like to know why certain codes happen the way they do. So, created a code to increment by 1 when a button is clicked and have that displayed on the screen. However, when using addEventListener, it didnt work. It only added 1 and never increased by 1 again.
But when I used onclick Event in html, it worked fine and incremented. What could be the issue? Here are the codes:
HTML
<div class="score container">
<h3 class="firstScore">0</h3>
<h3 class="to">To</h3>
<h3 class="secondScore">0</h3>
Player One
JS code with addEventLister. This doesnt increment, But when I used consol.log(count), it increased by 1 but grayed out. Kindly check the attached screenshot
var playerOne = document.querySelector('.playerOne')
playerOne.addEventListener('click', () => {
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
}
countNum()
})
This is the JS code that I used onclick and added the function to the button directly. This is working fine. I want to know what made the addEventListener not to work?
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
console.log(count)
}
The button with the html:
<button onclick="countNum()" class="playerOne">Player One</button>
You're resetting count to 0 every time the function is called.
You need to use the inner function as the event listener, not the outer function. You can do this with an IIFE that returns the inner function.
var playerOne = document.querySelector('.playerOne')
playerOne.addEventListener('click', (() => {
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
}
return countNum;
})())
<div class="score container">
<h3 class="firstScore">0</h3>
<h3 class="to">To</h3>
<h3 class="secondScore">0</h3>
<button class="playerOne">Player One</button>
You should move your var count = 0 outside from addEventListener function. Otherwise on each click you will reset your counter and then immediately increment it, which means you always assign to innerHTML value equal to 1.
Fixed example with addEventListener:
var playerOne = document.querySelector('.playerOne');
var firstScore = document.querySelector('.firstScore');
var count = 0;
var countNum = function() {
count++;
firstScore.innerHTML = count;
};
playerOne.addEventListener('click', countNum);
Working example.

button OnClick event not firing

There is a page and I am trying to attach an onclick event to the button ("SEARCH CRUISES") on the page but the onclick event is not firing correctly. Here is my code:
<script>
debugger;
var x = document.getElementsByClassName("cdc-filters-search-cta")
for (i=0; i< x.length; i++){
if(x[i].text.trim().indexOf("SEARCH") >= 0 && x[i].text.trim().indexOf("CRUISES") >= 0){
x[i].onclick = function(){
console.log("Search button clicked");
};
break;
}
}
Here is the complete html: https://jsfiddle.net/g0tkqrx6/
I have tried attaching the onclick event to the object in many different ways but I am not able to get the click event to fire. I would appreciate if anybody can provide some insight as to what I could be doing wrong here.
Thanks in advance
Seeing your html would be helpful. Make sure you are interacting with the correct names for your js events.
You must use textContent for element text and make it uppercase.
Here is an example:
var x = document.getElementsByClassName("cdc-filters-search-cta")
for (var i=0; i< x.length; i++){
var element = x[i] ;
if((element.textContent ).toUpperCase().indexOf("SEARCH") >= 0 && element.textContent.toUpperCase().indexOf("CARS") >= 0){
element.onclick = function(){
console.log("Search button clicked");
};
break;
}
}
<button class="cdc-filters-search-cta"> SEARCH</button>
<button class="cdc-filters-search-cta"> CARS</button>
<button class="cdc-filters-search-cta">SEARCH CARS</button>
Well to start with I think you should really take a look at this article on why you shouldn't add inline functions or css.
https://www.tomdalling.com/blog/coding-styleconventions/why-inline-comments-are-generally-a-bad-idea/
Secondly I think your issue is that you are trying to add a click event to an angular front end which is controlled by the ngModel and also the site is probably compiled AOT. However you can try this,
let x = document.querySelectorAll('.cdc-filters-search-cta');
let term = /[(SEARCH)(CRUISES)]/
x = Array.from(x);
x.forEach(span => {
if (term.test(span.textContent)) {
return span.addEventListener('click', (e) => {
console.log('span clicked')
});
}
})
I changed your code to querySelectorAll which returns an array and I used a forEach loop to add an eventListener. Not sure how well that will go down with your angular, but maybe.

Switch on / off Links on the page with one button: toggle() two functions

I've written a working code for the two buttons:
HTML:
<button class="OFF-LINK">OFF</button>
<button class="ON-LINK">ON</button>
<div class="box">...<a></a>...<a></a>...</div>
<div class="box">...<a></a>...<a></a>...</div>
Script:
$(".OFF-LINK").click(function off() {
var box = document.getElementsByClassName("box");
var x; for (x = 0; x < box.length; x++)
{box[x].innerHTML = box[x].innerHTML.replace( /href/ig,'hren');}
}); ///links stop working
$(".ON-LINK").click(function on() {
var box = document.getElementsByClassName("box");
var y; for (y = 0; y < box.length; y++)
{box[y].innerHTML = box[y].innerHTML.replace( /hren/ig,'href');}
}); ///links work again
How can I combine this two functions, to toggle them with one button?
You can achieve this by checking the returned match from RegEx pattern inside .replace() and swap it as per the below snippet
function toggleLinks() {
var box = document.getElementsByClassName("box");
var x;
for (x = 0; x < box.length; x++) {
box[x].innerHTML = box[x].innerHTML.replace(/hre(f|n)/gi,
g1 => {return (g1=="href") ? "hren" : "href"});
}
}
<button onclick="toggleLinks()">Toggle Links</button>
<div class="box">
google
<br>
<a href="http://www.yahoo.com" >yahoo</a>
</div>
<div class="box">
stackoverflow
<br>
<a href="http://www.github.com" >github</a>
</div>
I put some text in so you could see the changes
$(".OFF-LINK,.ON-LINK").on('click', function() {
var box = document.getElementsByClassName("box");
var x;
for (x = 0; x < box.length; x++) {
box[x].innerHTML = $(this).is('.OFF-LINK') ? box[x].innerHTML.replace(/href/ig, 'hren') : box[x].innerHTML.replace(/hren/ig, 'href');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="OFF-LINK">OFF</button>
<button class="ON-LINK">ON</button>
<div class="box">...
<a>href</a>...
<a>X</a>...
</div>
<div class="box">...
<a>href</a>...
<a>Y</a>...
</div>
How can I combine this two functions, to toggle them with one button?
If I'm understanding you correctly, you want to toggle the class on the button between on-link and off-link, and call the appropriate function afterwards? If so:
<button class="button off-link">Off</button>
$('body').on('click', '.button', function(){
$(this).toggleClass('off-link on-link');
if ($(this).hasClass('off-link')) {
$(this).innerHTML('Off');
// Do your 'off-link' code here
} else {
$(this).innerHTML('On');
// Do your 'on-link' code here
}
});
Generally, it's bad practice to replace all innerHTML, just to change a little detail. If you need to toggle links, would be better to find the required links and work only with their attributes:
$('.box a').each(function(){
var link = $(this).attr("href");
$(this).attr("data-link", link);
// saving each link in data-attribute
});
$('#toggle').on('click', function toggler(){
let on = toggler.on = !toggler.on; // (*1)
$('.box a').each(function(){
var link = $(this).attr("data-link");
$(this)[ on ? "removeAttr" : "attr" ]( "href", link ); // (*2)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="toggle">Toggle Links</button>
<div class="box">
link
link
</div>
<div class="box">
link
link
</div>
(*1) let on = toggler.on = !toggler.on; — each function is an object. You can work with it's name just like with common objects - setting him new properties or methods. I could declare a variable let on = true; out of the function, but decided to make everything inside. ! — it's the boolean "NOT": transforms false → true and vice versa. So, when you click the button, toggler.on is undefined (false), ! will become true and assign to itself (toggler.on = !toggler.on;) → the same value will be assigned to variable on.
At the next click, property toggler.on already will keep the true value, and become !true → false, and so on.
(*2) $(this)[ on ? "removeAttr" : "attr" ]( "href", link );
• Ternary operator, general form: (boolean expression) ? (return this value if true) : (else)
In this example, expression will return a "removeAttr" string, if on === true, and "attr" otherwise.
• Bracket notation. Mostly we use the dot notation, because it's shorter. Example, elem.innerHTML may be written as elem["innerHTML"]. Here I used a ternary expression, to pick the required method. Translation into if-else:
if( on ){
$(this).removeAttr("href")
} else {
var link = $(this).attr("data-link");
$(this).attr("href", link );
}
And the same code without jQ:
let links = document.querySelectorAll('.box a');
for( let i = 0; i < links.length; i++ ){
links[i].dataset.link = links[i].getAttribute("href");
}
let toggle = document.getElementById('toggle');
toggle.addEventListener('click', function toggler(){
let on = toggler.on = !toggler.on;
for( let i = 0; i < links.length; i++ ){
let link = links[i].dataset.link;
links[i][ on ? "removeAttribute" : "setAttribute"]("href", link);
}
});
<button id="toggle">Toggle Links</button>
<div class="box">
link
link
</div>
<div class="box">
link
link
</div>

Passing the id of another element into the onclick event of a button?

I am trying to make it so that when I click on a button above a clock element that I have, it changes it from am to pm. I have many clock elements, each associated with their own am/pm buttons. Here is what I tried (piechart0 is the clock and clock.js is where I handle my js for it):
<button class="button2" onclick="Clock.toAm("piechart0")">AM</button>
<button class="button2" onclick="Clock.toPm("piechart0")">PM</button>
<canvas id="piechart0" width="200" height="200"></canvas>
With this as my javascript:
Clock.toAm = function(id) {
var clock = document.getElementById(id);
clock.am = true;
for (var j = 0; j < 48; j++) {
clock.segments[j] = clock.amSegments[j];
clock.updateDraw(j);
}
}
Clock.toPm = function(id) {
var clock = document.getElementById(id);
clock.pm = true;
for (var j = 0; j < 48; j++) {
clock.segments[j] = clock.pmSegments[j];
clock.updateDraw(j);
}
}
But I get a "attribute piechart0 is not allowed here" notification. What am I doing wrong here/how can I pass in another id to the argument of a button's onclick argument?
EDIT: I see that I may be having quotation conflicts. Now, with using ' ' quotations I get the reference to piechart0, but whereas the actual piechart0 variables are all defined, when I complete:
var clock = document.getElementById(id);
All of this element's variables are undefined. I am not sure why this is the case since I am using the same id?
Change one of the double quotes to be single in the onclick prop
<button class="button2" onclick='Clock.toAm("piechart0")'>AM</button>
<button class="button2" onclick='Clock.toPm("piechart0")'>PM</button>
A couple suggestions:
For debugging this I would insert a console.log(id) and see what's actually getting through. Assuming you replace the quote mismatch with onclick="Clock.toPm('piechart0')" the value should get through just fine.
Since you have this tagged as jQuery, I would use .click() i.e. something like:
HTML
<button id="btnPm">PM</button>
Javascript:
$('button#btnPm').click(function() { Clock.toPm('piechart0'); });
As for clock.am, I'm not sure if modifying a DOM object like this can be made to work. For sure, though, it would be discouraged. I would suggest using .prop(), i.e. $(clock).prop('am', true)

Categories