How to keep track of which buttons have been pressed jquery - javascript

I want create simple calculator using only jquery. When I try to track which button is pressed from the list (name=numbers), it displays the value of the first button. For example, I constantly get 1
<html>
<head>
<script type="text/javascript" src="Z:\ПИ-313\2 подгруппа\Баталова Шаниязов\Веб - технологии\Веб - технологии\jquery-3.3.1.min.js"></script>
</head>
<body>
<div>
<input id="field" type="text"/>
<input type="button" value="<<">
<input type="button" value="C">
</div>
<div>
<button name="numbers" value="1">1</button>
<button name="numbers" value="2">2</button>
<button name="numbers" value="3">3</button>
<input type="button" value="+">
</div>
<div>
<input type="button" name="numbers" value="4">
<input type="button" name="numbers" value="5">
<input type="button" name="numbers" value="6">
<input type="button" value="-">
</div>
<div>
<input type="button" name="numbers" value="7">
<input type="button" name="numbers" value="8">
<input type="button" name="numbers" value="9">
<input type="button" value="*">
</div>
<div>
<input type="button" name="numbers" value="0">
<input type="button" value=",">
<input type="button" value="/">
</div>
<div>
<button id="calc">=</button>
</div>
<script>
$(document).ready(function(){
$(':button[name=numbers]').click(function() {
var number = $(':button[name=numbers]').val();
$('#field').val(number);
});
});
</script>
</body>

It is because with ':button[name=numbers]' you select all buttons with the name numbers, which, in your code snippet, means all of them. You get the first value: 1.
In Javascript you have this. In your click() function this is 'the item clicked'. In this case perfect, beause you want the value of 'the item clicked':
var totalSum = Number( $('#field').val() ); // easier to save if outside the click;
$(':button[name="numbers"]').click(function() {
$('#field').val( totalSum + this.value);
});
Little code review, this is what I've done:
Moved the totalSum out of the click. You can now do other computations with it, without having to select it from the DOM
I used this.value instead of $(this).val(). jQuery internally does the same, we just do it directly. Using native javascript where possible will very often be faster and more lightweight.
I just added the value directly in the .val() function. This will save you a line of code (while maintaining readability) and you don't save it in the memory now. It's a small value, but do this trick 1000 times and you will feel the difference. If you must save it in a variable, use let instead of var (and google why :) )
You use name= and them give them all the same name. They must be unique. I think you're looking for class=

You need to use $(this) to get the clicked button
$(document).ready(function(){
$(':button[name=numbers]').click(function() {
var number = $(this).val();
$('#field').val(number);
});
});

This is how I fixed it. Replace this:
var number = $(':button[name=numbers]').val();
$('#field').val(number);
by this:
var number = $(this).val();
$('#field').val($('#field').val() + number);
The mistake is that in your event you are always getting the first element instead of the clicked one.
Second is you are just setting the value of the retrieved data instead of concatenating with whats already existing.
Here is the JSfiddle demo

Related

How to save data in localstorage and access it on another html page

I am currently working on a laundry platform and right now I have 2 HTML page which is booking page and summary page. The booking page is where users can book the number of clothes to be washed using the plus and minus button, this would automatically calculate the total amount to be paid. Now I also want the summary page to display such information as the booking page. This actually mean the information would be stored in localStorage by booking page in order to be accessed by summary page and displayed to users.
<body>
<div class="second-booking-container">
<div>
<div class="second-booking-container-image"><img src="./img/shirt.png" /></div>
<p class="second-booking-container-icon" name="product" value="100" id="qnty_1">
Shirt(s)</p>
<p>
<button type="button" class="sub" data- target="shirt">-</button>
<input type="text" value="0" class="field_shirt" />
<button type="button" class="add" data-target="shirt">+
</button>
<p class="display_shirt" name="price" max="3" min="1">₦
100</p>
</p>
</div>
<div>
<div class="second-booking-container-image"><img src="./img/trouser.png" /></div>
<p class="second-booking-container-icon" name="product" value="100" id="qnty_2">
Trouser(s)</p>
<div>
<p>
<button type="button" class="sub" data target="trousers">−</button>
<input type="text" value="0" class="field_trousers" />
<button type="button" class="add" data-target="trousers">+
</button>
<p class="display_trousers" name="price" max="3" min="1">₦
0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img src="./img/skirt.png" /></div>
<p class="second-booking-container-icon" name="product" value="100" id="qnty_3">
Skirt(s)</p>
<div>
<p>
<button type="button" class="sub" data- target="skirts">−</button>
<input type="text" value="0" class="field_skirts" />
<button type="button" class="add" data- target="skirts">+</button>
<p class="display_skirts" name="price" max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img src="./img/blouse.png" /></div>
<p class="second-booking-container-icon" name="product" value="100" id="qnty_4">
Blouse(s)</p>
<div>
<p>
<button type="button" class="sub" data-target="blouses">-
</button>
<input type="text" value="0" class="field_blouses" />
<button type="button" class="add" data-target="blouses">+
</button>
<p class="display_blouses" name="price" max="3" min="1">₦
100</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img src="./img/jacket.png" /></div>
<p class="second-booking-container-icon-long" name="product" value="100" id="qnty_5">Suit/Jacket(s)
</p>
<p>
<button type="button" class="sub" data- target="suits">-</button>
<input type="text" value="0" class="field_suits" />
<button type="button" class="add" data-target="suits">+
</button>
<p class="display_suits" name="price" max="3" min="1">₦ 100</p>
</p>
</div>
</div>
<div class="third-booking-container">
<p>Total:₦ <span id="totalValue"></span></p>
<button>Set pick up date
<FontAwesomeIcon class="second-container-button-right" icon="angle-right" /></button>
</div>
</div>
Here is the JS code
var subElm = document.querySelectorAll('.sub');
var addElm = document.querySelectorAll('.add');
var totalValueElm = document.getElementById('totalValue');
for (var i = 0; i < subElm.length; i++) {
subElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
if (currentValue !== 0) {
var incValue = currentValue - 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
displayElm.innerHTML = "₦" + strValue;
totalValueElm.innerText = Number(totalValueElm.innerText) -
100;
}
});
addElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
var incValue = currentValue + 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
displayElm.innerHTML = "₦" + strValue;
totalValueElm.innerText = Number(totalValueElm.innerText) +
100;
});
}
Here is the second html page that I want to also show same information from the previous booking page
<body>
<div class="summaryContainer">
<div class="summaryNavBar">
<p className="summaryTitle">Summary</p>
</div>
<div class="summaryContent">
<p class="total" id="total">Total:</p>
<p class="sum">₦0.00</p>
</div>
<div class="summaryCard">
<div class="summary-card-title">
<div>Item</div>
<div>Quantity</div>
</div>
<div class="summary-card-content">
<div>Shirt(s)</div>
<div id="
first" class="summary-quantity"><button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button> </div>
</div>
<div class="summary-card-content">
<div>Trouser(s)</div>
<div class="summary-quantity" id="second">
<button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content" id="third">
<div>Suit(s)</div>
<div class="summary-quantity"><button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button> </div>
</div>
<p class=" more">..more</p>
</div>
<div class="summaryButton">
<button class="button-left"><span>
<FontAwesomeIcon class="buttonLeft" icon="angle-left" /></span>Back</button>
<button class="button-right">Proceed to
payment
<FontAwesomeIcon class="buttonRight" icon="angle-right" /></button>
I want all information or data entered by user in booking page to be displayed on summary include each number on the plus and minus button too.
If I understand correctly you are having trouble using the LocalStorage API
The MDN page contains detailed examples on how to use localStorage or sessionStorage.
To set a value:
localStorage.setItem('nameOfItem', 'yourValue'); // The value must always be a string
And to get a value:
let value = localStorage.getItem('nameOfItem');
Note: since you explain that you are in dire need of a solution, for what I assume is an assignement from your studies, I'll add the next step of code. But do keep in mind, that the solution that you are asking is not related to your question. For future references read up on this page to get your answer faster and better. This will benefit you!
Addition: So what you are struggling with is to get your totalValue stored in the the localStorage whenever, I assume, a user want's to set a pickup date (based on your codepen). This translates to the problem:
How to store value in localStorage on submit of a form?
So for this to work, you need two things.
<form> element
submit event listener
So why do you need those? The form can be debatable on wether or not you need it. It will enable you to submit all the values in your form without selecting all form elements manually, but can add a bit of complexity if you might just need one value out of all the code. I'll use it for this example so you can utilize the submit event of a form.
This submit event is fired whenever a type="submit" input or button in a form has been clicked. This will be useful in cases where you need to process multiple values simultaneously and do, for example, a validation check on all of the values of the input elements.
So wrap a <form> element around your code and set an id attribute to it. This will make it easy to select it when we need it. Modify the button at the end of your form and add type="submit" to it. This will make the form submit whenever that button is clicked.
<form id="book">
<!-- Put all the form fields inside here -->
<button type="submit" name="send">Set pick up date</button>
</form>
So, now you've created your form let's go over to the JavaScript side of things.
First thing you'll want to do it is select the form. You gave it an unique id so use document.getElementById to select it.
// Select the form.
var bookForm = document.getElementById('book');
Since you now can submit your form listen for the submit event on the form to do something whenever your form has been submitted.
Inside your event function get your totalValue, the same way that you've done earlier in your code, and store it in a variable.
So now you've got your totalValue. From here you can add it to your localStorage. See the code below:
// Listen for submit event on form.
bookForm.addEventListener('submit', function(event) {
// Get the total value
var totalValue = totalValueElm.innerHTML;
// Store the total value in the localStorage.
localStorage.setItem('totalValue', totalValue);
// Now redirect to your second page.
// Prevent form from default submitting.
// This is important. Removing this line will make the form submit
// to the server and reload the page.
event.preventDefault();
});
You would now have stored your totalValue into the localStorage. And the value will be overwritten whenever you submit the form again.
So now on your next page you'll want to check if a value is stored in the localStorage. This part is explained at the top of my answer, but you'll need to add some checking to it.
var totalValue = localStorage.getItem('totalValue');
if (totalValue !== null) { // null is whenever no item of `totalValue` exists.
// Do something with your value.
}
So that's about it. This is as far as I can bring you. If you encounter any more problems try to open up a new thread on SO or ask a peer for help.
I hope you will be able to finish your project.
Best of luck!

Write 1 JavaScript Statement that will take text from the text boxes and use it to set the border of the paragraph when the button is clicked

I need to add a single JavaScript statement in the function clickHandler() to make sure the input from the text boxes form a border around the first paragraph. I know that the getElementById only accepts one element not multiple however this approach is also not working. Would very much appreciate any help. This is all the code involved.
<head>
<script>
function clickHandler(){
document.getElementById('para1').style.border =
document.querySelectorAll('#size, #style, #colour).value;
}
</script>
</head>
<body>
<h1>Introduction to JavaScript</h1>
<p id="para1">JavaScript is also known as ECMAScript.</p>
<p>Size:
<input type="text" id="size">
</p>
<p>Style:
<input type="text" id="style">
</p>
<p>Colour:
<input type="text" id="colour">
</p>
<button type="button" onclick="clickHandler()" value="Change style">Change style</button>
You might use Array.from to transform a NodeList of each input into an array of each input's values, then join by spaces:
function clickHandler() {
document.getElementById('para1').style.border = Array.from(
document.querySelectorAll('input'),
input => input.value
).join(' ');
}
<p id="para1">JavaScript is also known as ECMAScript.</p>
<p>Size:
<input type="text" id="size" placeholder='5px'>
</p>
<p>Style:
<input type="text" id="style" placeholder='solid'>
</p>
<p>Colour:
<input type="text" id="colour" placeholder='green'>
</p>
<button type="button" onclick="clickHandler()" value="Change style">Change style</button>

Ajax update works for radios, checkboxes but not a button

On click, I want the form to process and update based on which button is clicked.
html:
<input type="button" value="5.00" name="updatefield" id="updatefield" class="chooseit">
have also tried:
<button name="updatefield" id="updatefield" class="chooseit">5.00</button>
<button name="updatefield" id="updatefield" class="chooseit" type="button">5.00</button>
<button name="updatefield" id="updatefield" class="chooseit" type="button" value="5.00">5.00</button>
<button name="updatefield" id="updatefield" class="chooseit" type="submit" value="5.00">5.00</button>
When I change button to anything besides "button," (radio,checkbox, etc) the form process as expected. (The 5.00 is passed to the overall page total as +5.00)
View.js:
events: {
'click button.chooseit': 'chooseIt',
},
processing.js
chooseDonate: function(updatefield) {
this.set('updatefield', updatefield);
var that = this;
$.post('index.php?route=info/updateinfo', this.toJSON(), function(data) {
qc.event.trigger('updateAll', data);
that.updateForm(data);
}, 'json').error();
},
Are buttons handled differently? Can't figure out why radios/checkboxes work, but not buttons.
I'm not familiar with the framework you are using. If I understand events:{'click button.chooseit': 'chooseIt',} you bind the click to a function called chooseIt. It would be nice to see that function too.
But to answer your question "Are buttons handled differently?", well, it depends on what type of button. There are <input type="button">, <input type="submit">, <input type="image">, <input type="reset">, <button type="button">, <button type="submit">, <button type="menu"> and <button type="reset">. If type="submit" or type="image" the form is submitted. If type="reset" the controls in the form are reset to their initial value. If type="menu" a popup menu defined via its designated <menu>-element is displayed. If type="button" nothing special happens unless you have added a click-handler.
For the thing you are trying to do, there is no difference in plain javascript. I have added an example below where I use <input type="radio">, <input type="checkbox">, <input type="button">, <button type="button"> and <select>, and they are all using the same function to set the value of <output> to the latest clicked value. (type="checkbox" get special treatment since it can be clicked to uncheck)
So to find what's wrong, you need to dig into your framework and see what it is doing. A common mistake is that the form get submitted, and it can happen so fast that it looks like nothing happened. You can detect that, for example if you enable "sticky log" in your browsers developer console, so that the log is kept even if the page is reloaded.
var output = document.getElementById('output');
function setOutput(event) {
var value = this.value;
if (this.type === 'checkbox') {
if (!this.checked) value = '';
}
output.value = value;
}
document.querySelectorAll('input, button').forEach(
function (elem) {
elem.addEventListener('click', setOutput);
}
);
document.querySelectorAll('select').forEach(
function (elem) {
elem.addEventListener('change', setOutput);
}
);
fieldset{
display:inline-block;
width:150px;
height:50px;
vertical-align:top;
margin:0;
padding:0;
}
fieldset p {
margin:0;
padding:0;
font-size:80%;
}
<p>Proof of concept that the type of input element doesn't matter in this case.</p>
<form id="form1">
<fieldset>
<p><input type="radio"></p>
<label><input value="5" type="radio" name="radioValue">5</label>
<label><input value="10" type="radio" name="radioValue">10</label>
<label><input value="20" type="radio" name="radioValue">20</label>
</fieldset>
<fieldset>
<p><input type="checkbox"></p>
<label><input value="5" type="checkbox" name="chkValue">5</label>
<label><input value="10" type="checkbox" name="chkValue">10</label>
<label><input value="20" type="checkbox" name="chkValue">20</label>
</fieldset>
<fieldset>
<p><input type="button"></p>
<input value="5" type="button" name="ibtnValue">
<input value="10" type="button" name="ibtnValue">
<input value="20" type="button" name="ibtnValue">
</fieldset>
<fieldset>
<p><button type="button"></p>
<button value="5" type="button" name="btnValue">5</button>
<button value="10" type="button" name="btnValue">10</button>
<button value="20" type="button" name="btnValue">20</button>
</fieldset>
<fieldset>
<p><select></p>
<select>
<option value="">--Select value---</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</fieldset>
<fieldset>
<p>Last selected value: <output id="output"></output></p>
</fieldset>
</form>
If your button is inside a form, it's probably submitting it (that is their default behavior).
Try adding a type attribute to tell your browser you don't want that to happen:
<button name="updatefield" id="updatefield" class="chooseit" type="button">5.00</button>
You need to give the button a value such as below:
<button name="updatefield" id="updatefield" class="chooseit" type="button" value="5.00">5.00</button>

Use a button to input value in a form

I am looking to use an onclick button function in JQuery which when clicked returns the value in the button to the text area of a form. So for example I am building a calculator when i click 1 , 1 should be the value in the form input area. Any clues how i can do that?
<FORM NAME="Calc">
<TABLE BORDER=4>
<TR>
<TD>
<INPUT id ="enter" TYPE="text" NAME="Input" Size="16">
<br>
</TD>
</TR>
<TR>
<TD>
<button type ="submit" NAME="one" value="1"> 1 </button>
First brush up the basics of language
<button class="btncalc" value="1" type="button"></button>
$('.btncalc').click(function(){
$'#enter').val($(this).val());
});`
You could do something like this:
<input type="text" value="">
<button>1</button>
<button>2</button>
<button>3</button>
<script>
$( "button" ).click(function() {
var current = $("input").text();
var update = $( this ).text();
$("input").val( current + update );
});
</script>
I would avoid using <button type ="submit" NAME="one" value="1"> 1 </button> for your inputs in your calculator because this will cause a full form post due to type ="submit".
https://www.w3.org/TR/html-markup/button.submit.html
I grabbed most of the code from here (3/4 down the page). This will give you a feel for how it will work.
http://api.jquery.com/val/
Sounds like fun I hope it turns out nice :)

Need to get input text with javascript then add it to a sentence

Here is what I need so far. I need to have the quantity input box's value to be added to a sentence after the input area.
Right now I have this code for the input for quantity:
<label for="quantity">Qty: </label>
<input min="1" type="number" id="quantity" name="quantity" value="1" onkeyup="getVals(this, 'text');" />
<input type="submit" id="add-to-cart" class="btn addtocart" name="add" value="Add to cart" />
<div class="how-many">You have helped save <span id="pTextInput"></span>people</div>
I would like the input value for id quantity to be inserted into the span id="pTextInput".
So basically if the quantity input is set to 2 then the sentence, You have helped save 2 people would show up (the dynamic number being placed in the span.
Hope this makes sense. I can use regular javascript or jquery, whichever is easiest.
If I understood the question correctly, you might be looking for something like this:
<script type="text/javascript">
$(function() {
$("#pTextInput").html("1");
$("#quantity").on("change keyup", function() {
$("#pTextInput").html($(this).val());
});
});
</script>
<label for="quantity">Qty: </label>
<input min="1" type="number" id="quantity" name="quantity" value="1" />
<input type="submit" id="add-to-cart" class="btn addtocart" name="add" value="Add to cart" />
<div class="how-many">You have helped save <span id="pTextInput"></span> people</div>
As you change the input of quantity, the pTextInput value will change with it.
I guess you want this:
function getVals(input) {
document.getElementById("pTextInput").innerHTML = input.value;
}
Also, change getVals(this, 'text') to getVals(this) - no need for 'text'.
I would suggest taking a look at DOM manipulation basics with JS: http://www.w3schools.com/js/js_htmldom.asp

Categories