Sum Cookie value when I click a button - javascript

I have an input text and a button where a I put a number and storage this value in a Cookie using js-cookie clicking a button.
<input id="number" type="text" value="0">
<button id="send" type="button">SEND</button>
I want to sum each time I enter a number and show the result in an alert, so I tried in this way:
Jquery:
$("#number").keypress(function(e){
if(e.keyCode==13){
$("#send").click();
}
});
$("#send").click(function(){
var number= 0;
number+= parseInt($("#number").val(),10);
Cookies.set("numw", number);
});
var numw = Cookies.get("numw");
alert("Total: "+numw);
But this still showing the first number I sent.
I would like some help.

All you need is to add the number like:
$("#send").click(function(){
//var number= 0;
var numwTemp = Cookies.get("numw");
//number = parseInt($("#number").val(),10)) + parseInt(numwTemp, 10);
var number = parseInt($("#number").val(),10)) + parseInt(numwTemp || "0", 10);
Cookies.set("numw", number);
});
var numw = Cookies.get("numw");
alert("Total: "+numw);

Related

JQuery DOM manipulation: sum of 2 numbers generate NaN even if using parseInt()

I have multiple input type="number" on my page. They are dinamically generated each time a user clicks on a "add-form-row" button. I want to give as value to a h2 element in my DOM based on the sum of each of these input each time a new input is added. When I try to sum the inputs, though, a NaN is returned. How can I fix this?
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
//cloneMore('.form-row:last', 'elements');
// here starts the sum logic
var tot = 0;
currentTotal = $('.form-row').find('input[type=number]').each(function() {
numberPrice = parseInt($(this).val())
tot += numberPrice
});
$('.totalPrice').text(`<span>${tot}</span>`)
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="number" value="1">
<input type="number" value="2">
<button class="add-form-row">add</button>
<div class="totalPrice"></div>
</div>
If any of the input value is ="", i.e nothing, the total will be NaN, because parseInt("") = NaN, so maybe adding a condition like this can solve your problem:
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
//cloneMore('.form-row:last', 'elements');
// here starts the sum logic
var tot = 0;
currentTotal = $('.form-row').find('input[type=number]').each(function() {
if($(this).val() != ""){
numberPrice = parseInt($(this).val());
tot += numberPrice;
}
});
$('.totalPrice').text(`<span>${tot}</span>`);
return false;
});

Increment input field value with jQuery

I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});

Jquery :How to store textbox value clientside and display?

The below code will update the display value enter by user in textbox when button clicked but in this code it will not preserve the previous value enter by user .
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="textDiv"></div> -
<div id="dateDiv"></div>
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#textDiv").text(value);
$("#dateDiv").text(new Date().toString());
});
});
Now I want preserve all the value enter by user and when user will submit the button show both value previous as well as current.
How to achieve this ?
Can below code will help to preserve all the value
var $input = $('#inputId');
$input.data('persist', $input.val() );
If yes how to display all value previous,current etc. when user click on button ?
If i got this right, this is what you need?
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<script type="text/javascript">
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#section").prepend('<div class="textDiv">'+value+'</div>')
$("#section").prepend('<div class="dateDiv">'+new Date().toString()+'</div>')
$("#txt_name").val('');
});
});
</script>
<!-- each time you press submit, a new line will be pushed here -->
<div id="section">
</div>
If you want to display only the previous and current value the user submitted and use the data function then:
$("button").click(function() {
var input = $("#txt_name").val();
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',input);
$("#dateDiv").text(new Date().toString());
});
If you want all the values and you want to store them, then I would create an array. But you could always concatenate the string.
var arr = [];
$("button").click(function() {
var input = $("#txt_name").val();
arr.push(input);
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',previous+input);
$("#dateDiv").text(new Date().toString());
});
Without using .data() you can do this:
$("button").click(function() {
var input = $("#txt_name").val();
$("#textDiv").text($("#textDiv").text()+input);
$("#dateDiv").text(new Date().toString());
});
Instead of using two separate divs for message and date, you can use a single div.
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="msgDiv"></div>
$(document).ready(function() {
var preservedTxt = '';
$("button").click(function() {
var input = $("#txt_name").val();
var date = new Date().toString();
var msg = input + ' - ' + date;
preservedTxt = preservedTxt + '<br>' + msg;
$('#msgDiv').html(preservedTxt);
});
});
Jsfiddle : https://jsfiddle.net/nikdtu/p2pcwj2f/
Storing values in array will help
jQuery(function(){
var name=[];
var time=[];
$("button").click(function() {
var value = $("#txt_name").val();
name.push(value);
$("#textDiv").text(name);
time.push(new Date().toString())
$("#dateDiv").text(time);
});
});

How to manipulate value based on textbox value?

If I enter negative value in textbox, while in onclick the value will be reduced by some other value.
If I enter positive value in textbox, while in onclick the value will be add by some other values.
Make a simple comparison.
function go() {
var value = parseFloat(document.getElementById("value").value),
positiveValue = 5,
negativeValue = -1;
value += value < 0 ? negativeValue : positiveValue;
document.getElementById("value").value = value
}
<input id="value" onchange="go()">
Change the value of the textbox comparing it on button click.
HTML :
<input type="text" id="inputTextBox" />
<input type="button" id="changeButton" value="update value"/>
javaScript :
var paddingValue = 10;
document.getElementById("changeButton").onclick = function(){
var inputTextBox = document.getElementById("inputTextBox");
if(inputTextBox.value < 0){
inputTextBox.value = parseInt(inputTextBox.value) - paddingValue;
}else{
inputTextBox.value = parseInt(inputTextBox.value) + paddingValue;
}
};
jsFiddle demo

Passing JQuery value to html and then tally the totals with onclick

I am trying to pass on JQuery values to hidden textboxes (to send as a form later) as well as divs t
hat displays on the front end. I also want to tally these items as the value is passed to them. I have Frankensteined this bit of code which passes on the value to the the input boxes and the divs and it also tallies them onclick. I am just struggling to get the sum to display in #total_div. Can anyone point me in the right direction please?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#my_div').click(function() {
$('#my_value_1').val("100");
$('#my_value_1_div').html( "100" );
$('#my_div').click(addNumbers('total'));
});
});
$(document).ready(function(){
$('#my_div_2').click(function() {
$('#my_value_2').val("200");
$('#my_value_2_div').html( "200" );
$('#my_div_2').click(addNumbers('total'));
});
});
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
</script>
<h2>My pretty front end</h2>
<div id="my_div">ADD THIS VALUE 1</div>
<div id="my_div_2">ADD THIS VALUE 2</div>
VALUE 1: <div id="my_value_1_div">VALUE 1 GOES HERE</div>
VALUE 2: <div id="my_value_2_div">VALUE 2 GOES HERE</div>
TOTAL: <div id="total_div">SUM MUST GO HERE</div>
<h2>My hidden Form</h2>
Value 1: <input type="text" id="my_value_1" name="my_value_1" value="0"/>
Value 2: <input type="text" id="my_value_2" name="my_value_2" value="0"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
Total: <input type="text" id="total" name="total" value=""/>
EDIT
Ok so thanks to the advice I got the above working but now I need to clear the amounts. This is what I have done, it is almost there I think but I'm getting the incorrect sum.
$('#clear').click(function() {
$('#my_value_1').val('0');
$('#my_value_1_div').html( "0" );
$('#clear').click(minusNumbers('total'));
});
function minusNumbers()
{
var minval1 = parseInt(document.getElementById("my_value_1").value);
var minval2 = parseInt(document.getElementById("total").value);
var minansD = document.getElementById("total");
minansD.value = minval2 - minval1;
$('#total_div').text(minansD.value);
}
Update #total_div text in addNumber function as,
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
$('#total_div').text(ansD.value);
}
Demo
replace:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
with:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD = val1 + val2;
$('#total').val(ansD);
}
click(addNumbers('total')); first calls addNumbers with an unused parameter 'total' then gets the return value of addNumbers (null or undefined) and sets that as the click() handler for the next click.
I think you probably meant
$('#my_div').click(addNumbers);
that means, "run the addNumbers function, defined below, next time I click my_div".
or just
addNumbers();
that means, "run the addNumbers function now" (at the first click)
Note though that when you click and call addNumbers, one of the numbers may not yet be copied, so you would be adding 100+"" or ""+200 so you really have to think about what you want to do.

Categories

Resources