Trying to display button click results on screen - javascript

I'm a beginner trying to create an online calculator in JS. I made buttons, looped through them, and then created a function that looks to click and display numbers on the screen with innerHTML of the screen. but It is saying undefined. Here is the code.
var screen = document.getElementById("screen")
var allButtons = document.getElementsByClassName('buttons');
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', pressButton)
}
function pressButton(event){
var numID = this.id; // activates ID for each button the event listener above
screen.innerHTML = numID;
};

One example of how you could do it:
const screen = document.getElementById("screen")
const allButtons = document.getElementsByClassName('buttons');
Array.prototype.forEach.call(allButtons, (e) => e.addEventListener('click', () => screen.innerHTML += e.innerHTML));
<div id="screen"></div>
<br><br>
<div class="buttons">Button1 </div>
<div class="buttons">Button2 </div>
<div class="buttons">Button3 </div>

Did you add the id attribute to all the buttons you created? It is possible that it is saying undefined cause it can't find the id attribute.

<!DOCTYPE html>
<html>
<head>
<title>Online Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="calc.css">
</head>
<body>
<textarea id="screen" placeholder="0"></textarea>
<div class="buttonswrap">
<button id="num1" class= "buttons" value="1">1</button>
<button id="num2" class= "buttons" value="2">2</button>
<button id="num3" class= "buttons" value="3">3</button>
<button id="num4" class= "buttons" value="4">4</button>
<br>
<button id="num5" class= "buttons" value="5">5</button>
<button id="num6" class= "buttons" value="6">6</button>
<button id="num7" class= "buttons" value="7">7</button>
<button id="num8" class= "buttons" value="8">8</button>
<br>
<button id="num9" class= "buttons" value="9">9</button>
<button id="num0" class= "buttons" value="0">0</button>
<button id="plus" class= "buttons" value="+">+</button>
<button id="multiply" class= "buttons" value="*">*</button>
<br>
<button id="divide" class= "buttons" value="/">/</button>
<button id="minus" class= "buttons" value="-">-</button>
<button id="point" class= "buttons" value=".">.</button>
<button id="equals" class= "buttons" value="=">=</button>
</div>
<script type="text/javascript" src="calc.js"></script>
</body>
</html>
Here is my HTML

Related

Multiple buttons using same function

I have multiple buttons I would like to increment a value in different corresponding inputs. I am able to get all the buttons working but they only effect the first input. I realize I can write out three different functions for each button but I know there is a way to utilize one function. Thank you for any help in advance!
Here is code for reference:
let submit = document.querySelectorAll(".submit");
let num = document.querySelector(".num");
submit.forEach((btn)=>{
btn.addEventListener("click", increment);
});
let value = 0;
function increment(){
value +=1;
num.value = value;
}
<div class="container">
<div class="main">
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
</div>
</div>
Select the next sibling and select the input.
const submit = document.querySelectorAll(".submit");
submit.forEach((btn) => {
btn.addEventListener("click", increment);
});
function increment() {
const inp = this.nextElementSibling.querySelector("input");
inp.value = Number(inp.value) + 1;
}
<div class="container">
<div class="main">
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
</div>
</div>
That's how i would do it - basically in your "submit" buttons you create attribute (in this case "for" (see EDIT)) that will point to id of input to be incremented. This gives you full flexibility, no matter what html you have.
EDIT
Better use custom attribute, for example data-for, button doesn't have for attribute, as pointed in the comments below
let submit = document.querySelectorAll(".submit");
submit.forEach((btn)=>{
btn.addEventListener("click", increment);
});
function increment(ev){
let targetInputId = ev.target.getAttribute("data-for");
let targetInput = document.getElementById(targetInputId);
targetInput.value = parseInt(targetInput.value) + 1;
}
<div class="container">
<div class="main">
<button data-for="num1" class="submit">Submit</button>
<div class="withinDiv"><input id="num1" type="number" class="num" value="0"></input> </div>
<button data-for="num2" class="submit">Submit</button>
<div class="withinDiv"><input id="num2" type="number" class="num" value="0"></input> </div>
<button data-for="num3" class="submit">Submit</button>
<div class="withinDiv"><input id="num3" type="number" class="num" value="0"></input> </div>
</div>
</div>

When i click edit button all the buttons are getting clicked with same username

I'm making a app in which there is option for a user to add a comment and also to delete and modify it but when i click edit button , every button gets called and a edit block shows for every comment created by that user.
I'm running js on backend in node js,mongodb and express js as framework
...HTML
<div class='card-body'>
<%campground.comments.forEach(comment=>{ %>
<div class='row'>
<div class='col-md-12'>
<strong><%=comment.author.username%></strong>
<span class='float-right'>10 days ago</span>
<p ><%=comment.text %></p>
<%if(currentUser){ if(currentUser.username==comment.author.username) { %>
<form class='cmtForm py-3' action='/campgrounds/<%=campground._id%>/comments/<%=comment.author.username%>/<%=comment._id%>?_method=PUT' method='POST'>
<textarea class="form-control" rows="3" name='updateComment'><%=comment.text%></textarea>
<button class=' btn btn-success btn-sm m-3 float-right'>
Update
</button>
</form>
<button class='editBtn sel btn btn-secondary btn-sm float-right' id='<%=comment._id %>' >Edit</button>
<form action='/campgrounds/<%=campground._id%>/comments/<%=comment._id%>?_method=DELETE' method='POST'>
<button class='btn btn-danger btn-sm mr-2 float-right ' >Delete</button>
</form>
</div>
<%}}%>
</div>
</div>
<% }); %>
</div>
//..JS//
$('.cmtForm').css('display','none');
let status=true;
$('.editBtn').on('click',(event)=>{
if(status){
$('.sel').text('cancel');
$('.cmtForm').css('display','block');
// $('.cmtForm').addClass('cmtForm form-control show');
}
else{
$('.sel').text('edit');
$('.cmtForm').css('display','none');
// $('.cmtForm').removeClass('cmtForm form-control hide');
}status=!status;
});
//Edit button should unhide particular comment section
As I mentioned in the comment to the original post, you have the same class for all buttons where the action is performed and also the same class of elements you are changing on the click event. This is the reason when click action is performed all the comments etc. are changing.
Since every set of elements (comment, edit button, etc.) are enclosed within a div you may use siblings() function to select the specific elements for changing stuff.
Here is the demonstration with two rows having similar elements:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
console.log("ready");
$(".b").click(function () {
$(this).siblings('.h').text("hello");
});
});
</script>
<div>
<label class="h">first</label>
<button class="b">Edit</button>
</div>
<div>
<label class="h">second</label>
<button class="b">Edit</button>
</div>
The key part is:
// same button element
$(event.target).text('cancel');
// sibling
$(event.target).siblings('.cmtForm').css('display', 'block');
Your JS code after modification will look like the following. I removed dynamic elements to make it executable.
<div class='card-body'>
<div class='row'>
<div class='col-md-12'>
<strong>User 1</strong>
<span class='float-right'>10 days ago</span>
<p>Comment 1</p>
<form class='cmtForm py-3'
action='/campgrounds/<%=campground._id%>/comments/<%=comment.author.username%>/<%=comment._id%>?_method=PUT'
method='POST'>
<textarea class="form-control" rows="3" name='updateComment'>Comment 1</textarea>
<button class=' btn btn-success btn-sm m-3 float-right'>Update</button>
</form>
<button class='editBtn sel btn btn-secondary btn-sm float-right' id='<%=comment._id %>'>Edit</button>
<form action='/campgrounds/<%=campground._id%>/comments/<%=comment._id%>?_method=DELETE' method='POST'>
<button class='btn btn-danger btn-sm mr-2 float-right '>Delete</button>
</form>
</div>
</div>
<div class='row'>
<div class='col-md-12'>
<strong>User 2</strong>
<span class='float-right'>10 days ago</span>
<p>Comment 2</p>
<form class='cmtForm py-3'
action='/campgrounds/<%=campground._id%>/comments/<%=comment.author.username%>/<%=comment._id%>?_method=PUT'
method='POST'>
<textarea class="form-control" rows="3" name='updateComment'>Comment 2</textarea>
<button class=' btn btn-success btn-sm m-3 float-right'>Update</button>
</form>
<button class='editBtn sel btn btn-secondary btn-sm float-right' id='<%=comment._id %>'>Edit</button>
<form action='/campgrounds/<%=campground._id%>/comments/<%=comment._id%>?_method=DELETE' method='POST'>
<button class='btn btn-danger btn-sm mr-2 float-right '>Delete</button>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('.cmtForm').css('display', 'none');
let status = true;
$('.editBtn').on('click', (event) => {
if (status) {
$(event.target).text('Cancel');
$(event.target).siblings('.cmtForm').css('display', 'block');
// $(this).siblings('.cmtForm').addClass('cmtForm form-control show');
}
else {
$(event.target).text('Edit');
$(event.target).siblings('.cmtForm').css('display', 'none');
// $(this).siblings('.cmtForm').removeClass('cmtForm form-control hide');
}
status = !status;
});
</script>
Note: In your code, you are using a global variable status to control hide/display comment and changing button label. All rows (items) use the same status so you'll have an issue. Instead, you need to maintain status for every row (item).

How to keep selected the button on click of another button on same page using bootstrap?

On click of one of blue buttons(only one can be selected at a time) it is selected. But when I click on Buy button the previous blue button gets unselected. Therefore, I cannot read the value of blue button by onclick of yellow button.
Fiddle here.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<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">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sign in Success</title>
</head>
<body>
<div class="btn-group" style="background:black;width:100%">
<button type="button" class="btn btn-default">Tr</button>
<div style="width:10px"></div>
<button type="button" class="btn btn-default">T</button>
<div style="width:10px"></div>
<button type="button" class="btn btn-default">Vt</button>
<div style="width:10px"></div>
<button type="button" class="btn btn-default">Rt</button>
</div>
<br> <br>
<h2 style="text-decoration:underline;" align="center">T</h2>
<div align="center"><!-- id="centerit" -->
<br> <br> <br>
<!-- <div style="width:50px"></div> -->
<button type="button" class="btn btn-primary cust" value="bu">Butter</button>
<button type="button" class="btn btn-primary cust" value="mi">Milk</button>
<button type="button" class="btn btn-primary cust" value="bi">Biscuit</button>
<br> <br>
<button type="button" class="btn btn-warning" value = "submit">Buy!</button>
</div>
</body>
</html>
I expect the blue button to remain selected when i click on buy button which is not happening now.
You can put your buttons in a form and replace the three blue buttons with radio buttons. See the documentation here:
https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons
Updated fiddle: https://jsfiddle.net/0wj1m8ce/
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
<label class="btn btn-primary cust">
<input type="radio" name="options" id="option1" autocomplete="off" value="bu"> Butter
</label>
<label class="btn btn-primary cust">
<input type="radio" name="options" id="option2" autocomplete="off" value="mi"> Milk
</label>
<label class="btn btn-primary cust">
<input type="radio" name="options" id="option3" autocomplete="off" value="bi" > Biscuit
</label>
</div>
Try adding radio buttons instead of buttons
That is what you required
<div id="radioBtn" class="btn-group">
<a class="btn btn-primary btn-sm active" data-toggle="fun" data-title="bu">Butter</a>
<a class="btn btn-primary btn-sm notActive" data-toggle="fun" data-title="mi">Milk</a>
<a class="btn btn-primary btn-sm notActive" data-toggle="fun" data-title="bi">Biscuit</a>
</div>
<script>
$('#radioBtn a').on('click', function(){
var sel = $(this).data('title');
var tog = $(this).data('toggle');
$('#'+tog).prop('value', sel);
$('a[data-toggle="'+tog+'"]').not('[data-title="'+sel+'"]').removeClass('active').addClass('notActive');
$('a[data-toggle="'+tog+'"][data-title="'+sel+'"]').removeClass('notActive').addClass('active');
})
</script>
<style>
#radioBtn .notActive{
color: #3276b1;
background-color: #fff;
}
</style>
Here is an updated JSFiddle

trying to make a value true on click with an if statement

I am trying to change between colors on click in jquery. According to the picture below I have the default value
and then in this image when I click on the input box and then back on a button the background color stays on the input box rather than dissappears when any other button is clicked.
i'd like the background color to disappear when any of the buttons are clicked.
here is my jquery:
$("#donation-amount").click(function() {
if ($(this).hasClass('inpt-first')) {
$(this).css("background-color", "#c97e06");
$("#default").removeClass('active');
$("#btn2").removeClass('active');
$("#btn3").removeClass('active');
}
else{
$(this).removeAttr("background-color")
$("#default").addClass('active');
}
});
and here is my html:
<div class="choose-pricing">
<div class="btn-group">
<div class="buttons">
<button type="button" id="default" class="btn btn-default selectvalue hover-color active" value="50">50</button>
<button type="button" id="btn2" class="btn btn-default selectvalue hover-color" value="100">100</button>
<button type="button" id="btn3" class="btn btn-default selectvalue hover-color" value="150">150</button>
<input type="Custom" name="donation-amount" class="inpt-first form-control" id="donation-amount" onclick="if(this.defaultValue == this.value) this.value = ''" onblur="if(this.value=='') this.value = this.defaultValue" value="Custom">
</div>
<input type="hidden" name="donation-amount-value" id="donation-amount-value">
</div>
<div class="money-donate">
<div class="display-amount" id="display-amount">
</div>
</div>
</div>
</fieldset>
</div>
any help would be appreciated!
Try
$(this).css("background-color", "")
Instead of this
$(this).removeAttr("background-color")
You cannot remove the background-color like this as it is not an attribute.
On click of button you should remove the class active from the donation-amount
what you have written will only work as toggle on the custom button only. Its not interacting with rest of the buttons.
Flow should be to remove class from custom button if any button is hit and if custom button is hit remove class from any of button.
$(".selectvalue").each(function(){
$(this).click(function(){
$("#donation-amount").removeClass('active');
})
});
$("#donation").click(function(){
$(".selectvalue").removeClass('active');
})
Is this the functionality you are looking for? Also added in fiddle
Instead of background color, just use the .active class
$('#donation-amount,#default, #btn2, #btn3').click(function(event) {
//add any other checks you want here
$("#default").removeClass('active');
$("#btn2").removeClass('active');
$("#btn3").removeClass('active');
$("#donation-amount").removeClass('active');
$(event.target).addClass('active');
});
.active{
background-color:#c97e06;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="choose-pricing">
<div class="btn-group">
<div class="buttons">
<button type="button" id="default" class="btn btn-default selectvalue hover-color active" value="50">50</button>
<button type="button" id="btn2" class="btn btn-default selectvalue hover-color" value="100">100</button>
<button type="button" id="btn3" class="btn btn-default selectvalue hover-color" value="150">150</button>
<input type="Custom" name="donation-amount" class="inpt-first form-control" id="donation-amount" value="Custom">
</div>
<input type="hidden" name="donation-amount-value" id="donation-amount-value">
</div>
<div class="money-donate">
<div class="display-amount" id="display-amount">
</div>
</div>
</div>
I thought this code satisfied your requirement.
if your problem is not solve then write comment in explain then I can do it.
Please vote for me.
$("#donation-amount").click(function() {
if ($(this).hasClass('inpt-first')) {
console.log("hello");
$(this).css("background-color", "#c97e06");
$("#default").removeClass('active');
$("#btn2").removeClass('active');
$("#btn3").removeClass('active');
}
});
$("body").on("click","#default,#btn2, #btn3",function(){
//console.log($(this));
$("#donation-amount").css("background-color","rgb(255,255,255)");
//$("#default").addClass('active');
}
This seems a bit complicated the way you have it. This is a classic "choice highlight" scenario and is easily handled with a simple $(this).addClass('active').siblings().removeClass('active'); to set and remove the active highlight.
I also took the liberty of making the assumption you want some CUSTOM amount so I added a simple input for that to use with the CUSTOM button. I also simplified the custom button by using the data attribute and removed the code from that as frankly it seemed weird to have in there.
HTML with some adjustments:
<div class="choose-pricing">
<div class="btn-group">
<div class="buttons">
<button type="button" class="btn btn-default selectvalue hover-color choice default active " value="50">50</button>
<button type="button" class="btn btn-default selectvalue hover-color choice" value="100">100</button>
<button type="button" class="btn btn-default selectvalue hover-color choice" value="150">150</button>
<button type="button" class="btn btn-default selectvalue hover-color choice" value="" id="donation-amount" data-defaultvalue="57">Custom</button>
</div>
<input type="hidden" name="donation-amount-value" id="donation-amount-value">
</div>
<div class="money-donate">
<div class="display-amount" id="display-amount">
</div>
</div>
</div>
<div class="container">Custom Amount
<input id="customamount" type="text" value="67" />
</div>
Code that sets the color using an active class and sets the custom amount in the hidden field (or default if it has none)
$(".choice").on('click', function() {
if ($(this).is("#donation-amount")) {
var mydefault = $(this).data("defaultvalue");
// use custom amount if it has one, otherwise use this custom default
this.value = $('#customamount').val() || mydefault;
}
$(this).addClass('active').siblings().removeClass('active');
$('#donation-amount-value').val(this.value);
$('#display-amount').text('$'+this.value);
});
CSS:
.active {
background-color: #c97e06;
}
You can play around with it here: https://jsfiddle.net/MarkSchultheiss/6Lj62ngs/1/

Jquery - Click to copy parent element to text field

I want 4 buttons next to each URL, you can then click on a button to copy the parent url to the buttons respective textfield.
I presume that it is easiest to do this using jquery but I have no clue where to start. Any advice would be much appreciated!
http://jsfiddle.net/WwdMw/
<div class="selection">
<div class"url">
<h2>example1.com</h2>
</div>
<button type="button" class="btn_opt1">Copy to Option1</button>
<button type="button" class="btn_opt2">Copy to Option2</button>
<button type="button" class="btn_opt3">Copy to Option3</button>
<button type="button" class="btn_opt4">Copy to Option4</button>
</div>
<hr/>
<div class="selection">
<div class"url">
<h2>example3.com</h2>
</div>
<button type="button" class="btn_opt1">Copy to Option1</button>
<button type="button" class="btn_opt2">Copy to Option2</button>
<button type="button" class="btn_opt3">Copy to Option3</button>
<button type="button" class="btn_opt4">Copy to Option4</button>
</div>
<hr/>
<div class="selection">
<div class"url">
<h2>example2.com</h2>
</div>
<button type="button" class="btn_opt1">Copy to Option1</button>
<button type="button" class="btn_opt2">Copy to Option2</button>
<button type="button" class="btn_opt3">Copy to Option3</button>
<button type="button" class="btn_opt4">Copy to Option4</button>
</div>
<hr/>
Have it.
$('button').click(function () {
var value = $(this).parent().find('h2').text();
var idIdentifier = $(this).text().substr($(this).text().length - 1);
var textArea = $('div[class*='+idIdentifier+']').find('textarea');
textArea.val(textArea.val() +" "+ value);
})
Live Demo

Categories