I have two buttons which either increment or decrement an input value. I don't know how to retrieve the value later on submit of the result. My current attempts have either resulted in 'undefined' or '0'.
Thanks in advance for any advice
$('.plus').click(function(e){
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal)) {
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
$(".minus").click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
//attempting to get value
var value = document.getElementById( 'inputval' ).val();
$('#submitscore').click(function() {
alert(value);
});
My HTML
<span class="input-group-btn">
<button class="btn btn-secondary btn-success minus" field='minusfield' id ="minus" type="button">-</button>
</span>
<input type="text" name="inputval" id="inputval" value="0" class="gh form-control" />
<span class="input-group-btn">
<button class="btn btn-secondary btn-success plus" id="plus" field='plusfield' type="button">+</button>
</span>
<button type="button" id="submitscore" class="btn btn-md btn-orange">Submit</button>
You are attempting to get already assigned value.
Change your code to this
$('#submitscore').click(function() {
alert($('#inputval').val());
});
and it should work.
You're mixing standard Javascript usage with jQuery usage when you try to call it like this:
//attempting to get value
var value = document.getElementById( 'inputval' ).val();
Use one or the other:
Standard Javascript:
document.getElementById('inputval').value
jQuery:
$('#inputval').val()
Related
Hi guys I'm building a simple e-commerce site from scratch rather then using Shopify and I've made all the simple front end bits however i cant seem to get the total price to update based on the quantity of products the customers picks.
So far if the customer "adds to cart" then the price and total number in cart will update by 1, but if they want to choose 2 or more it doesn't work and i was wondering how i can get it to work
HTML:
<button class="addcart btn btn-danger add-to-cart" type="button">Add to cart</button> //Button to add to cart
<div class="input-group plus-minus-input"> //Quantity of product
<div class="input-group-button">
<button class="button hollow circle1 btn btn-primary"
data-field="quantity" data-quantity="minus" type="button">
<i aria-hidden="true" class="fa fa-minus"></i>
</button>
</div>
<input class="input-group-field" name="quantity" type="number" value="0">
<div class="input-group-button">
<button class="button hollow circle2 btn btn-primary"
data-field="quantity" data-quantity="plus" type="button">
<i aria-hidden="true" class="fa fa-plus"></i>
</button>
</div>
</div>
<p class="cartPrice">0.00 kr</p><input id="search-submit" type="submit"> //Quantity in cart
Javascript:
//Quanity animation when the user clicks + or -
jQuery(document).ready(function(){
$('[data-quantity="plus"]').click(function(e){
e.preventDefault();
fieldName = $(this).attr('data-field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal)) {
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
$('[data-quantity="minus"]').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('data-field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
});
//When the user clicks add to cart this will update the total price and the quantity in the cart
var currentItems = 0;
var cartPrice = 565.00;
$(document).ready(function(){
$(".add-to-cart").click(function(){
currentItems++;
var totalPrice = currentItems * cartPrice;
$(".cart-badge").text(currentItems);
$(".cartPrice").text(totalPrice + " kr")
});
});
So again I'm just trying to figure out when the user clicks on + to add more prodcuts i want the price to update to that: So if the user wants 5 products it will do 5 * 565 etc.
Thanks
When you click "add to cart" nothing is retrieving the current quantity and so it is always static. By retrieving the value from the quantity input box your math will work correctly.
currentItems = $("input.input-group-field[name='quantity']").val();
//Quanity animation when the user clicks + or -
jQuery(document).ready(function(){
$('[data-quantity="plus"]').click(function(e){
e.preventDefault();
fieldName = $(this).attr('data-field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal)) {
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
$('[data-quantity="minus"]').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('data-field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
});
//When the user clicks add to cart this will update the total price and the quantity in the cart
var currentItems = 0;
var cartPrice = 565.00;
$(document).ready(function(){
$(".add-to-cart").click(function(){
currentItems = $("input.input-group-field[name='quantity']").val();
var totalPrice = currentItems * cartPrice;
$(".cart-badge").text(currentItems);
$(".cartPrice").text(totalPrice + " kr")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="addcart btn btn-danger add-to-cart" type="button">Add to cart</button> //Button to add to cart
<div class="input-group plus-minus-input"> //Quantity of product
<div class="input-group-button">
<button class="button hollow circle1 btn btn-primary" data-field="quantity" data-quantity="minus" type="button">-<i aria-hidden="true" class="fa fa-minus"></i></button>
</div>
<input class="input-group-field" name="quantity" type="number" value="0">
<div class="input-group-button">
<button class="button hollow circle2 btn btn-primary" data-field="quantity" data-quantity="plus" type="button">+<i aria-hidden="true" class="fa fa-plus"></i></button>
</div>
</div>
<p class="cartPrice">0.00 kr</p><input id="search-submit" type="submit"> //Quantity in cart
I implemented a page with 2 buttons which call 2 different functions on their button clicks. But the any of the buttons are not working. They are just reload the same page. I'll put my code down below.
<form class="form-horizontal" id="add_product_form" method="post">
<script>
function submitForm(action)
{
document.getElementById('add_product_form').action = action;
document.getElementById('add_product_form').submit();
}
</script>
<div class="col-sm-12">
<input type="submit" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="submit" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
</div>
Any help would be really appreciated. Thank you! Add_to_cart function which is mentioned above the page.
function check_add_to_cart(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
return true
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
function check_add_to_quote(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
return true
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
}
You can do following. Change typesubmit to button And as you already have submitForm() method. Call this method when you want to return true.
Change
<input type="submit" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="submit" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
To
<input type="button" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="button" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
And change your js functions to:
function check_add_to_cart(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
//return true
submitForm(""); //you can pass action in this if you want other page
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
function check_add_to_quote(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
//return true
submitForm(""); //you can pass action in this if you want other page
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
}
And remove submitForm() definition between html and add it to script block
I want to be able to increment and also decrement a value (5) and I would like to cover this with one function (I know how to do it with two).
Unfortunately I am not able to get it done and can't figure out what is wrong.
Here is my code:
HTML:
<form>
<button type="button" value="minus" onclick="updateAmount();">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount();">
+
</button>
</form>
JS:
var num = parseInt(document.getElementById('number');
var btn = document.querySelector('button');
btn.addEventListener('click', updateAmount);
function updateAmount(){
btn.value === "minus" ? num-- : num++;
document.getElementById('number').value = num;
}
Also at JSfiddle
I would prefer a vanilla JS solution if possible, but any suggestion is welcome :)
Thanks!
The minimal-changes to your approach is to pass an argument to the function:
function updateAmount(value) {
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(-1);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(1);">
+
</button>
</form>
Or use your value attribute and pass this into the function:
function updateAmount(btn) {
var value = btn.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
That latter approach combines nicely with modern event handling:
// Scoping function so our `updateAmount` isn't global
(function() {
document.querySelector("button[value=minus]").addEventListener("click", updateAmount);
document.querySelector("button[value=plus]").addEventListener("click", updateAmount);
function updateAmount() {
var value = this.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
})();
<form>
<button type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus">
+
</button>
</form>
You could hand over the action as a parameter
<form>
<button type="button" value="minus" onclick="updateAmount('minus');">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount('plus');">
+
</button>
</form>
and then
function updateAmount(action) {
var num = parseInt(document.getElementById("number").innerHTML, 10);
switch(action) {
case 'minus':
num--;
break;
case 'plus':
num++;
break;
}
document.getElementById("number").innerHTML = num;
}
You can try this ...
<html>
<form>
<button type="button" value="minus" onclick="updateAmount(this.value);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this.value);">
+
</button>
</form>
<script>
function updateAmount(value){
var num = parseInt(document.getElementById('number').innerHTML);
value=='plus'?num++:num--;
document.getElementById('number').innerHTML = num;
}
</script>
</html>
You were close, as you have multiple elements use document.querySelectorAll() with valid selector to get there reference and bind event handlers.
As you are using <SPAN> element, it doesn't have value property, need to use textContent property.
var btns = document.querySelectorAll('button');
btns.forEach(function(btn) {
btn.addEventListener('click', updateAmount);
});
function updateAmount() {
var num = parseInt(document.getElementById('number').textContent.trim(), 10);
this.value === "minus" ? num-- : num++;
document.getElementById('number').textContent = num;
}
<button type="button" value="minus">-</button>
<span id="number">5</span>
<button type="button" value="plus">+</button>
Note: Get rid of ugly inline click handlers.
simply use like this updateAmount(this)
function updateAmount(that) {
var number = document.getElementById('number');
var num = parseInt(number.innerHTML);
num = (that.value == "minus") ? --num : ++num;
number.innerHTML = num;
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
var minusBtn = document.querySelector('#minus');
var plusBtn = document.querySelector('#plus');
minusBtn.addEventListener('click', updateAmount('minus'));
plusBtn.addEventListener('click', updateAmount('plus'));
function updateAmount(action) {
return function() {
var numberElem = document.getElementById('number');
var number = numberElem.innerText;
number = parseInt(number, 10);
if (action === 'minus') {
number--;
} else if(action === 'plus') {
number++;
} else {
throw new Error('invalid operator');
}
numberElem.innerText = number;
};
}
<form>
<button id = "minus" type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button id = "plus" type="button" value="plus">
+
</button>
</form>
this is a good example for curry function, you can currify your updateAmount to accept action as a part of argument
Your code has just two small flaw, rest is perfect.
Firstly Your variable num is evaluating to NaN.
Secondly you should use textContent instead of value .
I am sharing correct way to evaluate num and then it will work.
var el =document.getElementById('number')
var num = parseInt(el.textContent);
Again, while updating
document.getElementById('number').textContent = num
Hope it helped.
I have simple plus and minus button on either side of input field as in the code below
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />
with aim to add or subtract rooms while adding rooms and the jquery functions as
function add() {
var a = $("#noOfRoom").val();
a++;
if (a => 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
but the following problems are shown
when i click on subtract (-) button at the initial phase -1 is shown in input box, where by default the subtract (-) button should be disabled to make rooms number negative.
Each time when I click on PLUS or MINUS buttons the numbers are added or subtracted by 2. How could I solve it?
Update add a fiddle https://fiddle.jshell.net/n7ug52dr/
Each time you click will only add and sub by 1, and it never show the -1
You can edit code like this:
function add() {
var a = $("#noOfRoom").val();
a++;
if (a && a >= 1) {
$("#subs").removeAttr("disabled");
}
$("#noOfRoom").val(a);
};
function subst() {
var b = $("#noOfRoom").val();
// this is wrong part
if (b && b >= 1) {
b--;
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
};
Moving comments to answer as no-one took onboard the suggestions:
I suggest not using inline onclick= handlers with jQuery. They separate the event handler from the event code for no reason and don't allow for the extra features of jQuery event handlers.
Use prop and not attr for DOM element properties (like disabled). This has the extra advantage of taking a boolean value.
You can then simply use !a to control the disabled state (as you are only checking for 0).
As a good habit always select DOM elements once and save the selector.
e.g.
$('#adds').click(function add() {
var $rooms = $("#noOfRoom");
var a = $rooms.val();
a++;
$("#subs").prop("disabled", !a);
$rooms.val(a);
});
// Set initial disabled state
$("#subs").prop("disabled", !$("#noOfRoom").val());
$('#subs').click(function subst() {
var $rooms = $("#noOfRoom");
var b = $rooms.val();
if (b >= 1) {
b--;
$rooms.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});
JSFiddle: https://jsfiddle.net/k7nyv84b/4/
Here you go, champ! Made your code a little cleaner as well
See the working example below
$(function(){
$('#adds').on('click',add);
$('#subs').on('click',remove);
});
function add(){
var input = $('#noOfRoom'),
value = input.val();
input.val(++value);
if(value > 0){
$('#subs').removeAttr('disabled');
}
}
function remove(){
var input = $('#noOfRoom'),
value = input.val();
if(value > 0){
input.val(--value);
}else{
$('#subs').attr('disabled','disabled');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%"/>
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="0" name="noOfRoom" />
<input type="button" value="+" id="adds" class="btn btn-default" />
take a look at this solution
<input type="button" value="-" id="subs" onclick="subst()" disabled>
<input type="text" id="noOfRoom">
<input type="button" value="+" id="adds" onclick="add()">
function add() {
var a = $("#noOfRoom").val();
a++;
if (a >= 1) {
$("#subs").removeAttr("disabled");
}
alert(a);
$("#noOfRoom").val(a);
}
function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
b--;
alert(b);
$("#noOfRoom").val(b);
}
else {
$("#subs").attr("disabled", "disabled");
}
//alert('works well');
}
The simplest way is to use DOM to navigate through elements and get its current value and then increase/decrease them.
I extended the code to make sure when minus button is clicked value isn't reduce below zero.
<input type="button" value="-" class="qtyminus" field="quantity">
<input type="number" class="input-lg" id="quantity" name="quantity" value="1" min="1" style="padding:0px;height:30px;">
<input type="button" value="+" class="qtyplus" field="quantity">
<input type="submit" name="add" id="add" class="btn btn-large btn-border btn-dark" value="GET IT NOW" style="opacity: 1;">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
<button onClick="myfun()">+</button>
<!--<button onClick="myfun()" id="pluse">+</button>-->
<input type="text" id="pluse" >
<button onClick="myfun1()">_</button>
var a = 0;
function myfun(){
a++;
document.getElementById('pluse').value = a;
//document.getElementById('pluse').innerHTML = a;
}
function myfun1(){
a--;
document.getElementById('pluse').value = a;
}
Please.. i need a help with this thing..
I wanna use a variable ID in HTML, to call a function in javascript page.
Example:
html
(MINUS BUTTON DONT WORK)
<button class="minus-button quantity-button button" type="button" name="subtract" onclick="javascript: subtractDiv2(document.getElementById('<ccom:field id='Code' />'));" value="-"> </button>
(THIS INPUT QUANTITY WORKS NORMAL)
<input class="quantity-input" value="<ccom:field id="Qtd"/>" maxlength="3" id='<ccom:field id="Code" />' name="div2" onkeypress="return somenteNumerico(event);"/>
(PLUS BUTTON WORKS NORMAL)
<button class="plus-button quantity-button button" type="button" name="add" onclick="javascript:document.getElementById('<ccom:field id='Code' />').value++;" value="+"></button>
javapage
function subtractDiv2(){
if(value - 1 < 0)
return;
else
value--;
};
You're not using the argument to the function. It should be:
function subtractDiv2(div) {
var value = parseInt(div.value, 10);
if (value < 1) {
return;
} else {
div.value = value - 1;
}
}