Pass a Value from Button to Text Field in JavaScript - javascript

I'm trying to pass a number to a text field on button click. User hits "add to cart" and the 2499 is added to the total already in the text field.
<form name="cart">
<input id="display" type="text" name="output" size="6" placeholder="0000"/>
<button id="scart" value="Add to Cart" onclick="addCart()" +='2499'"/>
<script type="text/javascript">
var total=""
function addCart(){
document.getElementById('scart').value;
total+= document.getElementById('display').value;
console.log(total);
}
</script>
When learning, I feel that I understand the logic, but don't know the syntax.

I think this is what you want. I made a codepen for you: https://codepen.io/NeilGBK/pen/boGadz?editors=1111
<form name="cart">
<input id="display" type="text" name="output" size="6" placeholder="0000"/>
</form>
<button id="scart" onclick="addCart(2499)">Add To Cart</button>
<script>
function addCart(v){
document.getElementById('display').value = v
console.log(v);
return false;
}
</script>
I'm passing the number to the function and simply using that to change the value of the input. I'm also logging it to the console

You have some errors, your quotes are not matching and you don't have closing button tag. Also, why don't you add 2499 in the code?
How about this:
<form name="cart">
<input id="display" type="text" name="output" size="6" placeholder="0000"/>
<button id="scart" value="Add to Cart" onclick="addCart()" >
</button>
<script type="text/javascript">
var total=""
function addCart(){
document.getElementById('scart').value;
total+= document.getElementById('display').value + 2499;
console.log(total);
}
</script>
</form>

It's not clear what you are trying to do so I made the beginning of a "cart" button where the input is the quantity you want to add to cart.
I then print out the number typed in and the total if you pressed the button more than once.
<input id="display" type="text" name="output" size="6" placeholder="0000" />
<button id="scart" type="button">Add to cart</button>
<script type="text/javascript">
var total = 0;
var display = document.querySelector('#display');
var scart = document.querySelector('#scart');
scart.addEventListener('click', function() {
var str = display.value;
var num = parseInt(str, 10);
console.log('You entered the number: ', num);
if (!isNaN(num)) {
total += num;
}
console.log('The total is now: ', total);
});
</script>

There are many things that is wrong here:
First, replace + with a good indicator data-value or whatever
<button id="scart" value="Add to Cart" onclick="addCart()" data-value="2499"/>
Second, In your script you should make var total a number not string.
var total = 0;
Finally, your addCart() function.
function addCart() {
// I see you are trying to get the value of the clicked button so you need to store it as this does not do anything
// document.getElementById('scart').value;
var value = document.getElementById('scart').value;
// Add it to total var;, you need to parseInt it as .value returns string
total += parseInt(value);
// put it on display
document.getElementById('display').value = total;
}
Hope that helps.

Related

showing the result of multiply two input value in a div called result

I just want to show the result in this div ,i tried to use nodeValue instead value and call the finalCalc fun in js file but it show nothing when i click on the button.
var billValue=document.getElementById("dollars").value,
peopleValue=document.getElementById("people").value,
theResult=document.getElementById("result"),
calculateButton=document.getElementById("calculateButton");
function calculateTip(x,y){
var reso=x*y;
theResult.innerHTML=reso;
}
function finalCalc() {
calculateTip(billValue,peopleValue);
}
<form>
<label>how much was your bill?</label>
<label for ="dollars">$</label>
<input value ="0" type="text" id="dollars" placeholder="Bill Amount ">
<br>
<label for="people">How many people are sharing the bill?</label>
<input value ="0" type="text" id="people">
<button type="button" id="calculateButton" onclick()="finalCalc()">CALCULATE</button>
<div id="result"></div>
</form>
onClick is written as onClick="" instead of onclick()="", reworked your code a little, hope this helps.
var billValue = document.getElementById("dollars").value,
peopleValue = document.getElementById("people").value,
theResult = document.getElementById("result"),
calculateButton = document.getElementById("calculateButton");
function calculateTip(x, y) {
return x * y;
}
function finalCalc() {
theResult.innerHTML = calculateTip(billValue, peopleValue);
}
<button type="button" id="calculateButton" onClick="finalCalc()">CALCULATE</button>

Buttons to increment/decrement a value on screen

I have something like this in an HTML file:
<html>
<body>
<script type = text/javascript">
var value = 0;
add(x){
x++;
document.write(x);
}
</script>
<form>
<input type = "button" value = "Add one" onClick = "add(value)" >
</form>
<body>
</html>
When I run this and click the button, the page will just update and display only the new value. How can I change this so that it's just a real time update, and the "Add one" button remains on the screen?
I think I need to have something like a "field" to display the value, and just get that field id, but I'm not sure if that's the right way of thinking.
Just use a span:
<form>
<input type="button" value="Add one" onclick="add();"/>
</form>
<span id="field">0</span>
Then, use document.getElementById() and innerHTML to update it:
var value = 0;
function add() {
value++;
document.getElementById("field").innerHTML = value;
}
var value = 0;
function add() {
value++;
document.getElementById("field").innerHTML = value;
}
<form>
<input type="button" value="Add one" onclick="add();"/>
</form>
<span id="field">0</span>
In your html add an id in a div for example addOne
<html>
<body>
<script type = text/javascript">
var x = 0;
function increment(value){
document.getElementById('addOne').innerHTML = ++x;
}
</script>
<form>
<input type = "button" onClick = "increment(value)" >
</form>
<div id ="addOne"></div>
<body>
</html>

Global Arrays value assigning issue

I am trying to assign values to div by a global array (in ascending function) . but the array is always empty in ascending function. Please also mention the best practice in this case.
I wish to set an array in one function , and in the other function I wish to use the same populated array . but after entering all the values I found that page get refresh and the values assign to array and Hidden1 field are set to empty again.
<html>
<head>
<script type="text/javascript">
var array = new Array();
function get_strings(m)
{
i = 1;
do
{
var ArrayElement=prompt("Please Enter a Number");
i++;
array.push(ArrayElement);
}
while (i <= m);
document.getElementById('print').InnerHtml = array;
document.getElementById('Hidden1').value = array;
};
</script>
<script>
function ascending()
{
var x = document.getElementById('Hidden1').value;
document.getElementById('print').InnerHtml = x;
};
</script>
</head>
<body>
<h2>Enter Number of elements</h2>
<br /><br />
<form>
<input id="Hidden1" type="hidden" value="" />
<input id="num" type="text" name="elements"> <br> <input type="submit" value="Submit" text= "Take Input" onclick="get_strings(document.getElementById('num').value)">
<br />
<input type="submit" value="Ascending" text= "Ascending" onclick="ascending()">
</form>
<div id="print"></div>
</body>
</html>
Page got refreshed because you are clicking the submit button, it's just the basic desired behavior when clicking on a submit button. Which brings the question, do you intend to submit this value to the backend? If so what you need to do is to have your backend return the value after the form POST.
If you do not intend on submitting this value, then use a regular button instead of a submit button.

Trying to calculate the total price of items taking into account the quantity selected Javascript

this is my first time posting on this site. i have a webpage that outlines one of my products that I intent to sell
here is my dilemma. I have this code that asks the user to press + and - buttons for the quantity of the item that they want. Now what i am trying to work out is if the user presses + or - any number of times I need to be able to to take into account the number of clicks and calculate the total price for the order on a separate line. Im very new to javascript all help is appreciated thanks
<form>
<br> Item Price: $463.50
<br> Please Select Quantity
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
<input type='button' name='add' onclick='javascript: document.getElementById("qty").value++;' value='+'/>
<input type='text' name='qty' id='qty' />
</form>
<form>
<br> Item Price: $<span id='price'>463.50</span>
var unitprice = (document.getElementById('price').innerText || document.getElementById('price').textContent);
var price = parseFloat(unitprice);
var count = parseInt(document.getElementById("qty").value, 10)
var total = price * count;
alert(total); // or do whatever you want
I would separate out the Javascript code into its own <script> element, and do something like:
<form>
<br/> Item Price: $<span id="price">463.50</span>
<br/> Please Select Quantity
<input type="button" name="subtract" id="subtract" value="-"></input>
<input type="button" name="add" id="add" value="+"></input>
<input type="text" name="qty" id="qty" value="0"></input>
<br/> Total
<input type="text" name="total" id="total" value="0"></input>
</form>
The Javascript would look like:
$(function() {
var price = parseFloat($('#price').text());
$('#subtract').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
if ( current > 0 ) {
$qty.val(current-1);
$('#total').val(price*(current-1));
} else {
$('#total').val(0);
}
});
$('#add').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
$qty.val(current+1);
$('#total').val(price*(current+1));
});
});
You can see it in action.
This is all do-able without jQuery, but it makes life a lot easier!
Since you mentioned you're new to this, a word of WARNING: In the real app only use the quantity from the page, and re-calculate out how much to charge them on the back end. It would be very easy for someone to modify either the price or total in the DOM; if you were to use the price or total from the DOM then a malicious user could buy it for any price they wanted! Always assume input is malicious or incorrect.
var value = parseInt(document.getElementById("qty").value, 10)
item_price = item_price * value;
document.getElementById("someid").innertHTML = item_price;

Javascript Adding Two Fields Together for Tiggzi App

I need some help putting together a line of javascript. I Am looking to add the values of two different fields and display them in a text area. The fields are "AP" and "MP" and the text are is "TotalCost".
I am not sure of how to make his happen at all. Please help!
HTML:
<input name="AP" />
<input name="MP" />
<textarea name="TotalCost" rows="4" cols="20"></textarea>
<button>Add</button>
jQuery:
$(document).ready(function(){
$("button").click(function(){
$("textarea[name='TotalCost']").val($("input[name='AP']").val()+$("input[name='MP']").val());
});
});
Working fiddle
So something like:
<input id="AP" />
<input id="MP" />
<input id="TotalCost" />
<button onclick="add()">Add</button>
<script>
function add()
{
var ap = +document.getElementById('AP').value; // Value of AP (plus will cast the value to a number)
var mp = +document.getElementById('MP').value; // Value of MP
document.getElementById('TotalCost').value = ap + mp; // Set TotalCost to ap + mp
}
</script>
If you wanted to use jQuery, you could do something like this:
<button id="btnAdd">Add</button>
<script>
$('#btnAdd').click(function ()
{
var ap = +$('#AP').val();
var mp = +$('#MP').val();
$('#TotalCost').val(ap + mp);
});
</script>

Categories