Populating a text box with the results of a calculation - javascript

I have this form where a user enters price and quantity, soon after the mouse leaves the 'Quantity' text box, I want the TotalPrice text box to be populated with result of Price * Quantity. The following is my jQuery code, however the TotalPrice text box does not get populated with the result. Hope someone can advise me on how to go about getting it right.
$("#quantity").mouseleave (function () {
var i = $("#price").val();
var k = $("#quantity").val();
var total = i*k;
$("#totalprice").val(total);
});

You need to use blur event handler of those two textboxes. Try this:
$(document).ready(function() {
$("#price").on("blur", calculate);
$("#quantity").on("blur", calculate);
//If you want to do the calculation when the page renders:
calculate();
});
function calculate(){
var i = $("#price").val();
var k = $("#quantity").val();
var total = i*k;
$("#totalprice").val(total);
}
As trincot mentioned in the comment below, you can merge the two events in one line since they call the same function:
$("#price, #quantity").on("blur", calculate);

I think you want this
jQuery(document).ready(function($) {
var price = $("#price");
var qty = $("#quantity");
var total = $("#totalprice");
/* CREATE VARIABLES ON DOCUMENT READY,
BECAUSE YOU WANT TO CACHE THE DOM SELECTION */
qty.on("blur", function(){
var i = price.val();
var k = qty.val();
total.val(i * k);
});
});
working fiddle ==> https://jsfiddle.net/tonysamperi/xqxm3900/

The problem with your code is that it is getting executed ONLY ONCE as soon as the ready function is called.
You need to attach a listner to the action element
$(document).ready(function() {
$("#quantity").mouseleave(function(){
var i = $("#price").val();
var k = $("#quantity").val();
var total = i*k;
$("#totalprice").val(total);
});
});
You can use various event listners such as onchange, onfocusout, blur, onkeyup depending on how and when you want the changes to happen. For more info on types of events and all for jquery only - https://api.jquery.com/category/events/

Related

Calling a function with AJAX

I'm not sure how to explain this completely, but I hope this will make sense.
I have a function that I've made that calculates the remaining amount to spend to qualify for free delivery when the basket value total falls within certain thresholds.
The basket value is updated with AJAX every time a product is added to the basket.
The add to basket button appears in an AJAX generated modal.
I need my function to be called on every page refresh and also every time a product is added to the basket when the AJAX generated add to basket button is clicked. I'm trying to do all of this with the below, but it doesn't seem to work correctly. One of the problems is that the event fires multiple times when the add to basket button is clicked and another is that the basket total is updated after the event and so the total isn't calculated correctly.
Can anyone explain how I would tidy all off this up?
function totalBag() {
var standardDeliveryLow = 49.99;
var standardDeliveryHigh = 64.99;
var expressDeliveryLow = 65.00;
var expressDeliveryHigh = 99.99;
var bagValue = $('#basket-value').text();
var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));
if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
$('<div class="delivery-message"><p>£'+ standardDifference +' from standar delivery</p></div>').insertAfter('.breadcrumbs');
} else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
$('<div class="delivery-message"><p>£'+ expressDifference + ' from express delivery</p></div>').insertAfter('.breadcrumbs');
} else {
return false;
}
}
$(document).on('ajaxSuccess', function(e) {
$('[name="AddItemToBasket"]').on('click', function() {
$('body').bind('ajaxSuccess.custom', function() {
totalBag();
//alert('this works');
$(this).unbind('ajaxSuccess');
});
});
});
totalBag();
EDIT: Have fixed the issue where text was duplicating. Also have added comments for more understanding.
Had a check at the link you specified and tried the following modified code.
As per #ADyson, have removed the click event, which is fixing the multiple event firing.
Regarding your other problem, the total is updated after the event, yes the HTML is getting updated after the ajaxSuccess is triggered. Hence have used the ajaxSuccess event itself to get the basket amount and use it in totalBag fn.
It seems to be working. Kindly confirm:
//Adding empty div so that we can just update the value later
$(document).on('ready', function(){
$('<div class="delivery-message"></div>').insertAfter('.breadcrumbs');
})
function totalBag(bagTotal) {
var standardDeliveryLow = 49.99;
var standardDeliveryHigh = 64.99;
var expressDeliveryLow = 65.00;
var expressDeliveryHigh = 99.99;
//var bagValue = $('#basket-value').text();
//var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));
//Using a variable to store the calculated amount with text
var innerHTML = "";
if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
innerHTML= "<p>£"+ standardDifference +" from standar delivery</p>";
} else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
innerHTML= "<p>£"+ expressDifference +" from express delivery</p>";
} else {
return false;
}
//Updating the placeholder with new contents
$(".delivery-message").html(innerHTML);
}
//Gets triggered after every Ajax Success.
//e -> event object, xhr -> The Ajax object which has request and response details,
//settings -> The settings we used to trigger Ajax, including the request URL
$(document).on('ajaxSuccess', function(e, xhr, settings) {
//Checking if the request is of Adding Item to Basket
if(settings.url.indexOf("AddItemToBasket") !== -1){
//Getting the response and parsing it
var resp = xhr.responseText;
var respObj = JSON.parse(resp);
//Checking if response is success i.e., item added to cart successfully
if(respObj.success){
//Getting the updated Basket value and calling totalBag
var bagTotal = respObj.basket.subTotal;
totalBag(bagTotal);
}
}
});
totalBag(0);

Change value of first iteration input with next iteration input value

Structure Concept:-
Basically, i am trying to create the modal window containing input and that modal window currently fires when the input on index page get focused for that I have used data attribute to make a link between them by assigning them same attribute value.
Javascript Concept:-
for the modal window, I have created the modal object. and model object contains a bindModal method which takes one argument and that argument is data attribute value. after taking that value bindModal method will search dom elements containing that particular value and after the search, I iterate over them using each loop.
Problem
So basically I want whenever user starts typing on the model input it should get written automatically in input on the index page.
I will appreciate you all if guys help me out to make my code more optimized and well structured and most important thing is that let me know what mistake I have done in overall work Thanks
JavaScript Code
var modal = function () {
this.toggleModal = function () {
$('#modal').toggleClass('content--inActive').promise().done(function () {
$('#modal__close').on('click',function(){
$('#modal').addClass('content--inActive');
});
});
}
this.bindModal = function (bindVal) {
var bindValue = $(document).find('[data-modal-bind = ' + bindVal + ']');
$.each(bindValue, function (index) {
var bind1 = $(this);
if(index === 1) {
var bind2 = $(this);
$(bind1).change(function (){
$(bind2).val(bind1.val());
});
}
});
}
}
var open = new modal();
$('#input_search').on('click',function(){
open.toggleModal();
open.bindModal('input');
});
Here is one way to do what you want:
var modal = function() {
this.bindModal = function(bindVal) {
var bindValue = $('[data-modal-bind = ' + bindVal + ']');
bindValue.each(function(index) {
$(this).keyup(function() {
var value = $(this).val();
bindValue.each(function(i, e) {
$(this).val(value);
});
});
});
}
}
$('#input_search').on('click', function() {
var open = new modal();
open.bindModal('input');
});
Changes done:
I cached the inputs with same binding values in bindValue variable, and then bound the the keyup event for each of them. On keyup, the value of the current input is get in value, which is then assigned to each input using the inner loop.
This makes the inputs to be in sync while typing. Hope that solves your issue.

Click event object tracking woes

So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});

How to trigger an event after clicking two different button in Javascript

I was wondering how I can trigger an event after two different buttons being clicked. Specifically I have some buttons with different ids and I want when I click two specific buttons from them to trigger an event. I thought that this can be happen If I call some function in the first on click event and inside this function I can call another function if the second button being clicked. It does not seem to work, so I need your help. (If anyone needs more code please comment to upload the whole code)
function someKindOfFunction(){
//there is some other code here
var ob = document.getElementById(idTable[0]);
var ob1 = document.getElementById(idTable[1]);
var ob2 = document.getElementById(idTable[2]);
var ob3 = document.getElementById(idTable[3]);
ob.addEventListener("click",function() {onCl1(idTable[0],idTable)});
ob1.addEventListener("click",function() {onCl1(idTable[1],idTable)});
ob2.addEventListener("click",function() {onCl1(idTable[2],idTable)});
ob3.addEventListener("click",function() {onCl1(idTable[3],idTable)});
}
function onCl1(id1,idTable){
var obj1 = document.getElementById(id1);
obj1.disabled=true;
var obj2,v,obj3,obj4;
v=0;
var temp = ["0","0","0"];
for(var i =0 ; i<4 ; i++){
if( id1 != idTable[i]){
temp[v] = idTable[i];
v=v+1;
}
}
ob=document.getElementById(temp[0]);
ob1=document.getElementById(temp[1]);
ob2=document.getElementById(temp[2]);
ob.addEventListener("click",function() {onCl2(id1,temp[0])});
ob1.addEventListener("click",function() {onCl2(id1,temp[1])});
ob2.addEventListener("click",function() {onCl2(id1,temp[2])});
}
function onCl2(id1,id2){
//some kind of actions
alert("it wokrs");
}
Just pass some sort of value whenever the button you want is clicked. For instance:
ob.addEventListener("click",function() {onCl1(1)});
ob1.addEventListener("click",function() {onCl1(1)});
var i;
function onCl1(value){
i += value;
if(i == 2){
//do this
}
}
So basically once these two buttons are clicked the value will equal 2 and trigger whatever you want.

how to trigger jquery function when field automatically filled?

I have created an order form with multiple lines and columns
Product_id Qty price
Quantity and price are automatically filled out when Product is chosen in a drop down list.
At the end of the form, I have a field that sore the total amount <span id="total"></span>
I made the code below to calculate the total amount of the order but it doesn't work when qty and price are automatically filled. It does work if I type in qty or price
jQuery(function($) {
$(".qty, .price").change(function() {
var total = 0;
$(".qty").each(function() {
var self = $(this),
price = self.next(".price"),
subtotal = parseInt(self.val(), 10) * parseFloat(price.val(), 10);
total += (subtotal || 0);
});
$("#total").text(total);
});
});
You can use .trigger('change') or .change() while changing the textbox value from code:
$(".qty, .price").trigger('change');
or
$(".qty, .price").change();
For Example:
$(".qty").val('30').change();
I don't know if its correct but, have you tried using documnt.load()? you could put the code in a function that you call when page its loaded and when field value has changed.
You just need to separate you code into a new function such as:
var calculate = function() {
var total = 0;
$(".qty").each(function() {
var self = $(this),
price = self.next(".price"),
subtotal = parseInt(self.val(), 10) * parseFloat(price.val(), 10);
total += (subtotal || 0);
});
$("#total").text(total);
};
$(".qty, .price").change(calculate);
Then call it whenever you want.
Try calling a Function on page load and do it like this.
$( document ).ready(function() {
YourFunction();
YourFunction() function{
// insert your code
}
});
Then you can say
$(".qty, .price").change(function() {
YourFunction();
}

Categories

Resources