I have several forms for a product order page. Each Item on the page needs to have two prices, one for a one time order, and one for a recurring order.
The code I have is working fine, the problem is a need three javascript functions for each item, which as you can guess will get out of hand fast.
Here is the form for one product:
<form id="mangoForm" action="https://ximo365.foxycart.com/cart" method="post" accept-charset="utf-8">
<input type="hidden" name="name" value="Mango Bash Pack" />
<input id="mango-price-input" type="hidden" name="price" value="50" />
<input id="mango-sub-input" type="hidden" name="sub_frequency" value="1m">
<input id="mango-refBy" type="hidden" name="Referred By:" value="Not Specified">
<div class="btn-group">
<button type="button" onclick="changePriceLowMango()" class="btn btn-default">Subscribe & Save</button>
<button type="button" onclick="changePriceHighMango()" class="btn btn-default">One Time</button>
<button type="button" onclick="mangoSubmit()" class="btn btn-default" value="Submit form">Add To Cart</button>
</div>
</form>
And her is that forms javascript:
function changePriceHighMango() {
document.getElementById("mango-price").innerHTML = "80.00";
document.getElementById("mango-price-desc").innerHTML = "Switch to recurring and save up to 35%!";
document.getElementById("mango-price-input").value = "80.00";
document.getElementById("mango-sub-input").name = "Frequency";
document.getElementById("mango-sub-input").value = "Single Order";
}
function changePriceLowMango() {
document.getElementById("mango-price").innerHTML = "50.00";
document.getElementById("mango-price-desc").innerHTML = "Recurring Price. Cancel Anytime.";
document.getElementById("mango-price-input").value = "50.00";
document.getElementById("mango-sub-input").name = "sub_frequency";
document.getElementById("mango-sub-input").value = "1m";
}
function mangoSubmit() {
var mangoName = document.getElementById("distName").innerHTML;
document.getElementById("mango-refBy").value = mangoName;
document.getElementById("mangoForm").submit();
}
What I would like is three functions–one for increasing the price, one for decreasing the price, and one for submitting the form–that will work for each item. The functions would need to know which forms to change, what the low and high prices are, and what items on that form to update.
Is that at all possible to do?
Thanks for your help.
Trying to keep as much as the style and code you have right now, I would just pass all the variable stuff as arguments to a more generic changePrice function. As you say, the function would need to know which forms to change, what the low and high prices are, and what items on that form to update. So let's create a more generic changePrice function like this:
function changePrice(productName, description, price, subName, subValue) {
document.getElementById(productName + "-price").innerHTML = price;
document.getElementById(productName + "-price-desc").innerHTML = description;
document.getElementById(productName + "-price-input").value = price;
document.getElementById(productName + "-sub-input").name = subName;
document.getElementById(productName + "-sub-input").value = subValue;
}
function productSubmit(productName) {
var distName = document.getElementById("distName").innerHTML;
document.getElementById(productName + "-refBy").value = distName;
document.getElementById(productName + "Form").submit();
}
I am assuming that all the form inputs begin with the productName and have the same suffixes (-price, -price-desc, -price-input, -sub-input, and -sub-input).
Then you can just change the buttons onclick property with a call to those functions with the proper arguments.
<div class="btn-group">
<button type="button" onclick="changePrice('mango', 'Recurring Price. Cancel Anytime.', '50.00', 'sub_frequency', '1m')" class="btn btn-default">Subscribe & Save</button>
<button type="button" onclick="changePrice('mango', 'Switch to recurring and save up to 35%!', '80.00', 'Frequency', 'Single Order')" class="btn btn-default">One Time</button>
<button type="button" onclick="productSubmit('mango')" class="btn btn-default" value="Submit form">Add To Cart</button>
</div>
Example of a form for a **foo* product:
<form id="fooForm" action="https://ximo365.foxycart.com/cart" method="post" accept-charset="utf-8">
<input type="hidden" name="name" value="Foo Bash Pack" />
<input id="foo-price-input" type="hidden" name="price" value="50" />
<input id="foo-sub-input" type="hidden" name="sub_frequency" value="1m">
<input id="foo-refBy" type="hidden" name="Referred By:" value="Not Specified">
<div class="btn-group">
<button type="button" onclick="changePrice('foo', 'Foo Recurring Price. Cancel Anytime.', '10.00', 'sub_frequency', '1m')" class="btn btn-default">Subscribe & Save</button>
<button type="button" onclick="changePrice('foo', 'Foo Switch to recurring and save up to 35%!', '20.00', 'Frequency', 'Single Order')" class="btn btn-default">One Time</button>
<button type="button" onclick="productSubmit('foo')" class="btn btn-default" value="Submit form">Add To Cart</button>
</div>
</form>
You can try this:
function Mango(action) {
var mangoprice = document.getElementById("mango-price"),
mangopricedesc = document.getElementById("mango-price-desc"),
mangopriceinput = document.getElementById("mango-price-input"),
mangoprivesubinput = document.getElementById("mango-sub-input"),
mangorefBy = document.getElementById("mango-refBy"),
mangoForm = document.getElementById("mangoForm");
var mangoName = document.getElementById("distName").innerHTML;
switch(action)
{
case 'Low':
mangoprice.innerHTML = "80.00";
//... etc LOW PRICE
break;
case 'High':
//... etc HIGH PRICE
break;
case 'Submit':
mangorefBy.value = mangoName;
mangoForm.submit();
break;
}
}
Greetings from Vienna
Related
I have a basket of goods in which there can be many different entities. And I'm trying to implement changes in the number of goods using input - number without arrows, and with additional buttons +/-. I know that I could use identifiers and easily make my plans. But in my case, I need to use querySelectorAll. Help me please correct this code. quantity-arrow-minus decreases the field value and quantity-arrow-plus increases. How to make it so that the changes are concerned with each item?
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
node.addEventListener('click', function() {
update_cart.forEach(function(element) {
element.value = parseInt(element.value) - 1;
});
});
});
plus.forEach(function(node) {
node.addEventListener('click', function() {
update_cart.forEach(function(element) {
element.value = parseInt(element.value) + 1;
});
});
});
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
You can use previousElementSibling and nextElementSibling to access the input that corresponds to the button that was clicked:
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
node.addEventListener('click', function(e) {
const input = e.target.nextElementSibling
input.value = parseInt(input.value) - 1;
});
});
plus.forEach(function(node) {
node.addEventListener('click', function(e) {
const input = e.target.previousElementSibling
input.value = parseInt(input.value) + 1;
});
});
<form action="{% url 'cart:cart_update' %}" method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="0">
<button type="button" class="quantity-arrow-plus">+</button>
<br>
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="0">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
Use Number() instead. Assuming that the minus button will be just after your input, just use this.nextElementSibling. This is will make your code better instead of doing forEach on every element. What if there are many elements like these?
var minus = document.querySelectorAll('.quantity-arrow-minus');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach((node) => {
node.onclick = function () {
this.nextElementSibling.value = Number(this.nextElementSibling.value) - 1;
}
});
plus.forEach((node) => {
node.onclick = function () {
this.previousElementSibling.value =Number(this.previousElementSibling.value) + 1;
}
});
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
<br>
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
<br>
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
I am attempting to create a calculator using jQuery and JavaScript. My approach involves adding each entry (numbers and operators) to an array and then performing math on them. The calculator itself is incomplete as a cannot get the items in the array to sum/subtract/multiply/divide based on what button is clicked.
I've tried creating 2 separate arrays thinking the operator should not be either array, but that did not work and would create more issues down the road.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container w-25 align-left">
<form>
<div class="form-group">
<input type="text" class="form-control align-left" id="box" value='' placeholder="" readonly>
</div>
</form>
</div>
<div class='container w-25'>
<div class="container pb-2">
<button type="button" id='seven' value='7' class="num-btn btn btn-dark">7</button>
<button type="button" id='eight' value='8' class="num-btn btn btn-dark">8</button>
<button type="button" id='nine' value='9' class="num-btn btn btn-dark">9</button>
<button type="button" id='divide' value='/'class="op-btn btn btn-dark">/</button>
</div>
<div class="container pb-2">
<button type="button" id='four' value='4' class="num-btn btn btn-dark">4</button>
<button type="button" id='five' value='5' class="num-btn btn btn-dark">5</button>
<button type="button" id='six' value='6' class="num-btn btn btn-dark">6</button>
<button type="button" id='multiply' value='*' class="op-btn btn btn-dark">*</button>
</div>
<div class="container pb-2">
<button type="button" id='one' value='1' class="num-btn btn btn-dark">1</button>
<button type="button" id='two' value='2' class="num-btn btn btn-dark">2</button>
<button type="button" id='three' value='3' class="num-btn btn btn-dark">3</button>
<button type="button" id='minus' value='-' class="op-btn btn btn-dark">-</button>
</div>
<div class="container pb-2">
<button type="button" id='zero' value='0' class="num-btn btn btn-dark">0</button>
<button type="button" id='decimal' value='.' class="num-btn btn btn-dark">.</button>
<button type="button" id='plus' value='+' class="op-btn btn btn-dark">+</button>
<button type="button" id='equals' value='=' class="eq-btn btn btn-dark">=</button>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src='scripts.js'></script>
</html>
$('document').ready(function () {
var num1 = []; //creates array for first number set
var result = '';
$('.num-btn').click(function () {
num1.push($(this).prop('value')); //add each number to array
arr1 = num1.join(' '); //joins numbers without comma using ''
$('#box').val(arr1);
console.log(arr1);
result = (arr1);
console.log(result);
});
$('.op-btn').click(function () {
var operator = $(this).attr('value');
num1.push(operator);
console.log(operator);
$('#box').val(''); //clears input #box
console.log($('#box').val())
});
});
You can use eval function result = eval(arr1);
More reference at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
$('document').ready(function () {
var num1 = []; //creates array for first number set
var result = '';
$('.num-btn').click(function () {
num1.push($(this).prop('value')); //add each number to array
arr1 = num1.join(' '); //joins numbers without comma using ''
$('#box').val(arr1);
console.log(arr1);
result = eval(arr1);
console.log(result);
});
$('.op-btn').click(function () {
var operator = $(this).attr('value');
num1.push(operator);
console.log(operator);
$('#box').val(''); //clears input #box
console.log($('#box').val())
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container w-25 align-left">
<form>
<div class="form-group">
<input type="text" class="form-control align-left" id="box" value='' placeholder="" readonly>
</div>
</form>
</div>
<div class='container w-25'>
<div class="container pb-2">
<button type="button" id='seven' value='7' class="num-btn btn btn-dark">7</button>
<button type="button" id='eight' value='8' class="num-btn btn btn-dark">8</button>
<button type="button" id='nine' value='9' class="num-btn btn btn-dark">9</button>
<button type="button" id='divide' value='/'class="op-btn btn btn-dark">/</button>
</div>
<div class="container pb-2">
<button type="button" id='four' value='4' class="num-btn btn btn-dark">4</button>
<button type="button" id='five' value='5' class="num-btn btn btn-dark">5</button>
<button type="button" id='six' value='6' class="num-btn btn btn-dark">6</button>
<button type="button" id='multiply' value='*' class="op-btn btn btn-dark">*</button>
</div>
<div class="container pb-2">
<button type="button" id='one' value='1' class="num-btn btn btn-dark">1</button>
<button type="button" id='two' value='2' class="num-btn btn btn-dark">2</button>
<button type="button" id='three' value='3' class="num-btn btn btn-dark">3</button>
<button type="button" id='minus' value='-' class="op-btn btn btn-dark">-</button>
</div>
<div class="container pb-2">
<button type="button" id='zero' value='0' class="num-btn btn btn-dark">0</button>
<button type="button" id='decimal' value='.' class="num-btn btn btn-dark">.</button>
<button type="button" id='plus' value='+' class="op-btn btn btn-dark">+</button>
<button type="button" id='equals' value='=' class="eq-btn btn btn-dark">=</button>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src='scripts.js'></script>
</html>
What you're trying to do is actually a bit complex because particular string values (such as *) need to trigger particular operations (such as multiplication).
One way to handle this is with the operation function below. You would run this function once for each operation selected by the user.
The evaluate function assumes that you have already collected numbers into one array and operators into a separate array. (This separation helps to prevent type errors, and make it easy to tell how many operations need to be performed.) The function accumulates the mathematical result in the resultSoFar variable, and prints it when there are no operations left to perform.
let nums = [8, 5, 2];
let ops = ["*", "+"];
evaluate(nums, ops);
function operation(a, operator, b){ // eg: operation(8, "*", 5)
switch (operator){
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b; // This will fail spectacularly if b is zero
default:
console.log("Unknown operator: " + operator);
return NaN;
}
}
function evaluate(numsArray, opsArray){
// Requires numsArray to have exactly one item more than opsArray
if(opsArray.length + 1 != numsArray.length){
console.log("Error: Array lengths mismatch");
return; // Function will stop here if lengths aren't compatible
}
// Starts out with the first number
let resultSoFar = numsArray[0];
// We care about the index of each item, which is the second argument
// to the anonymous function that we pass to `Array.forEach`.
// The first argument is not important to us, as its name implies.
opsArray.forEach(function(_, index){
// Applies the operation to `resultSoFar` and the next number
resultSoFar = operation(resultSoFar, opsArray[index], numsArray[index + 1]);
// (In the example, there are two operations to perform:
// The first time through the loop, 8 * 5 = 40
// The second time through the loop, 40 + 2 = 42)
});
console.log(resultSoFar);
}
I leave it to you to collect the values from the user (and update the display after each entry.)
You might want to use the parseInt function to convert values from inputs into numerical values.
Note: The evaluate function could be implemented more succinctly by using the Array.reduce function, but this example uses more verbose syntax to be more easily readable by anyone unfamiliar with that (very useful) function.
Seeking assistance with creating add and subtract buttons within a form to add and remove amount of a line of stock.
Similar to:
I'm new to html and very new to javascript.
function minus(){
var bCount = parseInt(document.calculateCart.count.value);
var count = bCount--;
document.calculateCart.count.value = count;
}
function minus(){
var bCount = parseInt(document.calculateCart.count.value);
var count = bCount++;
document.calculateCart.bCount.value = count;
}
<div class="productForm">
<form name="calculateCart" action="#">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="int" name="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
If you want to chane your number using buttons and using text-input, you can change your code to that:
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="number" name="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
<script>
function minus(){
document.calculateCart.count.value = --document.calculateCart.count.value;
}
function add(){
document.calculateCart.count.value = ++document.calculateCart.count.value;
}
</script>
In HTML don't exist type of input - int, you need to use number or text.
If you want change value only using the buttons, you can make it like this:
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<span id="your-number">0</span>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
<script>
var a = 0;
function minus(){
a -= 1;
document.getElementById('your-number').innerHTML = a;
}
function add(){
a += 1;
document.getElementById('your-number').innerHTML = a;
}
</script>
Your both functions are named 'minus'. One of them (the second one) should be 'add'.
you have s sort of a typo in your code: your function for adding valus is called minus(). So you have two functions with the same name
I believe you are getting the value of count in a wrong way. You should assign an id to the input and use getElementById
working code:
function minus(){
var bCount = document.getElementById('count').value;
bCount--;
document.getElementById('count').value = bCount;
document.getElementById('count');
}
function add(){
var bCount = document.getElementById('count').value;
bCount++;
document.getElementById('count').value = bCount;
document.getElementById('count');
}
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="int" name="count" id="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
You need to use document.getElementById in order to get old textbox value.
Please check below code:
function minus(){
var oldVal = parseInt(document.getElementById("myVal").value);
oldVal--;
document.getElementById("myVal").value = oldVal;
}
function add(){
var oldVal = parseInt(document.getElementById("myVal").value);
oldVal++;
document.getElementById("myVal").value = oldVal;
}
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="text" id="myVal" name="count" value="0">
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
you have two function minus, one of them must be add
if you want use attributre name to select, you need to use something look like:
document.getElementsByName("count")[0].tagName
I have two buttons in my HTML:
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton()">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton2()" disabled="true">
</form>
I want to write a function() in JavaScript for when I click on button1 it should be disabled and change it's value to "not clickable" and button2 should be enabled and change it's value to "clickable" and the other way around.
I have written two functions but they aren't correct and I am very new to JavaScript. This is my functions():
function switcher() {
var btn = document.getElementById("knapp1");
btn.disabled = true;
}
function switcher2(){
var btn2 = document.getElementById("knapp2");
btn2.enabled = true;
}
You have a problem with the name of your function : switchButton() in your html and switcher in your js, the id are different too and enabled is not an html property. You can achieve what you want with only one function :
function switchButton(btn1, btn2) {
var btn1 = document.getElementById("button"+btn1);
var btn2 = document.getElementById("button"+btn2);
btn1.disabled = true;
btn1.value = "not clickable";
btn2.disabled = false;
btn2.value = "clickable";
}
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton(1,2)">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton(2,1)" disabled="true">
</form>
You should try to avoid have this duplicate logic that make the same, is very hard to maintain, I recommend to you instead use this:
function clickButton(e) {
const currentBtn = document.getElementById(e);
const otherBtn = document.getElementById(e === "knapp2"? "knapp1": "knapp2");
currentBtn.disabled = true;
otherBtn.disabled = false;
currentBtn.value="Not Clickable"
otherBtn.value="Clickable"
}
<form>
<input type="button" id="knapp1" value="Clickable" onClick="clickButton('knapp1')">
<input type="button" id="knapp2" value="Not Clickable" onClick="clickButton('knapp2')" disabled>
</form>
So I have a group of labels that all belong to the "btn btn-warning" bootstrap class:
<div class = "btn-group" data-toggle = "buttons">
<label class="btn btn-warning active">
<input type="radio" checked>QA 71</input>
</label>
<label class="btn btn-warning">
<input type="radio">QA 72</input>
</label>
<label class="btn btn-warning">
<input type="radio">QA 73</input>
</label>
<label class="btn btn-warning">
<input type="radio">QA 74</input>
</label>
<label class="btn btn-warning">
<input type="radio">ST 71</input>
</label>
<label class="btn btn-warning">
<input type="radio">PR/Beta</input>
</label>
</div>
I would like to assign IDs to all of them, with the one labeled QA 71 as environment1, the next one as environment2, etc. Here is my jquery function:
var count = 1;
var btnid = "";
$(document).ready(function(){
$("label .btn-warning").each(
function(){
btnid = "environment"+count;
$(this).attr("id", btnid);
count++;
});
});
However, this is not working. What am I doing wrong?
The reason it doesn't work, is because the selector is wrong, a label with a class is denoted as label.classname
jQuery's each() also already has a count in the first argument, use that
$(document).ready(function(){
$("label.btn-warning").each(function(index, elem){
elem.id = "environment" + (index + 1); // zero based
});
});
You could even use attr() with a callback
$(document).ready(function(){
$("label.btn-warning").attr('id', function(index){
return "environment" + (index + 1); // zero based
});
});
There is a space between label and btn-warning which mean it will try to look for a class inside label, which is not the case .
$("label.btn-warning")
JSFIDDLE