Trigger keyup on page load - javascript

In my code below I am not able to trigger the quantity function. Normally, when I execute the quantity function below I use keyup, i.e when I start typing in the quantity box.
However this time, in the quantity input box below I fetch a value from the database into it already so on page load I am expecting the function trigger to run that function. That is not working. How can I get this done?
$(document).ready(function() {
#foreach($products - > items as $item)
var item = $('#{!! $item->id !!}');
var ad = JSON.parse(item.attr('data-item'));
if (item.prop("checked")) {
$('.panel').append(
'<div class="container"> ' +
'<p class="name" >' + ad.name + '</p>' +
'<p class="price" data-price="' + ad.price + '">' + ad.price + '</p>' +
'<p class="total" ><span class="line-total" name="total" id="total"></span></p>' +
'<input size="50" type="text" class="form-control quantity" placeholder=" qty " name="quantity[]" value="{!!$item->pivot->quantity!!}" required/>' +
'</div>'
)
} else {
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
}
quantityFunction();
#endforeach
update
<script>
var quantityFunction => function() {
var container = $(this).closest('div');
var sum;
var quantity = Number($(this).val());
var price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
container.find(".total span").text(quantity * price);
container.find(".pts-total span").text(quantity * points);
sum = 0;
$(".line-total").each(function(){
sum = sum + Number($(this).text());
})
}
</script>

Why don't you put the quantity function into a non anonymous function and call it on document ready?
var quantityFunction = function() {
// your code here
}
and
$( document ).ready(function() {
quantityFunction ();
});
EDIT
JS Snipped:
var quantityFunction = function() {
var container = $(this).closest('div');
var sum;
var quantity = Number($(this).val());
var price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
container.find(".total span").text(quantity * price);
container.find(".pts-total span").text(quantity * points);
sum = 0;
$(".line-total").each(function() {
sum = sum + Number($(this).text());
});
}

Doesn't it have to be here?
$('.panel').on('trigger','click',function() { }

$('.panel').on('trigger','.quantity',function()
Which event you want to trigger on the .panel?
Correct format for .on jQuery method is
.on( events [, selector ] [, data ], handler )
eg:
$('.panel').on('click','.quantity',function() {} );
Changes to your updated code,
var $container = $('.panel').closest('div');
var sum;
var quantity = Number($('.quantity').val());
var price = Number($container.find('.price').data('price'));
points = Number($container.find('.points').data('points'));
$container.find(".total span").text(quantity * price);
$container.find(".pts-total span").text(quantity * points);

Related

Dynamically assign ID and attach data in JavaScript & jQuery using two nested for loops

I am having some trouble to get through this below jsfiddle task.
jsfiddle link
I want to do the same function using dynamic id.
I tried so many methods, but nothing works.
Please don't recommend to change the infrastructure. The page has been already designed the same kind of structure.
I need to achieve this same kind of function using two nested for loops with dynamic id.
HTML:
<div class="col-md-4" id="beforeDiv0">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId0" value="1000" />
</div>
</div>
<br/><br/>
<div class="col-md-4" id="beforeDiv1">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId1" value="1000" />
</div>
</div>
Javascript & jQuery:
$(document).ready(function(){
var newAmount = parseFloat(1000) + parseFloat(5);
for(var id=0; id<3; id++){
for (var i = 1; i < 3; i++) {
var html = '<tr style="height:50px;">';
html = html + '<td class="td-Amount" style="text-align: right; font-size: 15px; font-weight: bold;">';
html = html + 'Original: '+ '<span id="OrginalAmount' + i + '">' + 1000 + '</span><br/>' + 'New: <span id="Output' + id + "" + i + '">' + newAmount + '</span></td>';
html = html + '</tr>';
$(html).insertAfter("#beforeDiv" + id);
//var abc = id + "" + i;
//var xyz = '#textboxId' + id;
//var zyx = "Output"+id+""+i;
}
}
var myArr = new Array();
var myArr2 = new Array();
for(var id=0; id<3; id++){
var xyz = '#textboxId' + id;
myArr[id] = id;
for (var i = 1; i < 3; i++) {
myArr2[i] = i;
var calc = myArr[id] + "" + myArr2[i];
var zyx = "Output" + calc;
//below line is for dynamic id retrieval
/*
$(xyz).on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById(zyx).innerHTML = AmtChange;
});
*/
$("#textboxId0").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output01").innerHTML = AmtChange;
document.getElementById("Output02").innerHTML = AmtChange;
});
$("#textboxId1").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output11").innerHTML = AmtChange;
document.getElementById("Output12").innerHTML = AmtChange;
});
}
}
});
I looked at your code, and considered your comments, and if I understand you correctly, then something like this is what you are after:
$('input[id^=textboxId]').on("click change paste keyup", function() {
var id = $(this).attr('id');
id = id.replace(/\D/g,'');
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
/**
* The following could not really be simplified, because
* there are no defining data- attributes, or anything
* to identify the table rows as belonging to the textbox.
* When I tried to simplify the selection of "output" spans,
* a span with id Output111 would have been matched by Output11
* and Output1.
*/
$('#beforeDiv' + id).nextUntil('br').each(function(i,el){
$('span[id^=Output]', this).text(AmtChange);
});
});
I tested this on Codepen: https://codepen.io/skunkbad/pen/ayeVLp

VB.net non MVC RAZOR | Need help, javascript stack procress

I make a shopping website and have 2 menu, when i call page from ajax to show on my content zone (On DIV).
<script>
$(function () {
$("#chicken_tab2").click(function () {
$.ajax({
type: "POST",
url: "/view/Content/Index_cp.vbhtml",
datatype: "html",
success: function (data) {
$("#getcontent").html(data);
}
});
});
});
</script>
My content come to show but it can't use javascipt from _Layout.vbtml.
Then i put Main.js(it's Cart jquery)
<script src="~/view/Cart/main.js"></script>
inside main.js
jQuery(document).ready(function ($) {
//var getnum = $('#getnum').val();
//alert(getnum);
var cartWrapper = $('.cd-cart-container');
//product id - you don't need a counter in your real project but you can use your real product id
var productId = 0;
if( cartWrapper.length > 0 ) {
//store jQuery objects
var cartBody = cartWrapper.find('.body')
var cartList = cartBody.find('ul').eq(0);
var cartTotal = cartWrapper.find('.checkout').find('span');
var cartTrigger = cartWrapper.children('.cd-cart-trigger');
var cartCount = cartTrigger.children('.count')
var addToCartBtn = $('.cd-add-to-cart');
var undo = cartWrapper.find('.undo');
var undoTimeoutId;
var getnum = $('.getnum');
//-----------------------------------------------------------------------------------------------------
//O function Strat
//O function End
//add product to cart
addToCartBtn.on('click', function(event){
event.preventDefault();
addToCart($(this));
});
//open/close cart
cartTrigger.on('click', function(event){
event.preventDefault();
toggleCart();
});
//close cart when clicking on the .cd-cart-container::before (bg layer)
cartWrapper.on('click', function(event){
if( $(event.target).is($(this)) ) toggleCart(true);
});
//delete an item from the cart
cartList.on('click', '.delete-item', function(event){
event.preventDefault();
removeProduct($(event.target).parents('.product'));
});
//update item quantity
cartList.on('change', 'select', function(event){
quickUpdateCart();
});
//reinsert item deleted from the cart
//undo.on('click', 'a', function(event){
// clearInterval(undoTimeoutId);
// event.preventDefault();
// cartList.find('.deleted').addClass('undo-deleted').one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
// $(this).off('webkitAnimationEnd oanimationend msAnimationEnd animationend').removeClass('deleted undo-deleted').removeAttr('style');
// quickUpdateCart();
// });
// undo.removeClass('visible');
//});
}
function toggleCart(bool) {
var cartIsOpen = ( typeof bool === 'undefined' ) ? cartWrapper.hasClass('cart-open') : bool;
if( cartIsOpen ) {
cartWrapper.removeClass('cart-open');
//reset undo
clearInterval(undoTimeoutId);
undo.removeClass('visible');
cartList.find('.deleted').remove();
setTimeout(function(){
cartBody.scrollTop(0);
//check if cart empty to hide it
if( Number(cartCount.find('li').eq(0).text()) === 0) cartWrapper.addClass('empty');
}, 500);
} else {
cartWrapper.addClass('cart-open');
}
}
function addToCart(trigger) {
var ids = trigger.data('ids');
var item = trigger.data('item');
var cartIsEmpty = cartWrapper.hasClass('empty');
//update cart product list ****add trigger in ()
addProduct(trigger.data('item'),trigger.data('detail'), trigger.data('productname'), trigger.data('pic'), $('#' + ids + '').val());
//update number of items
updateCartCount(cartIsEmpty);
//update total price
updateCartTotal(1, true);
//show cart
cartWrapper.removeClass('empty');
}
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}
function addProduct(item, detail, product, pic, QTY) {
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
productId = productId + 1;
//var productAdded = $('<li class="product"><div class="product-image"><img src="Cart/product-preview.png" alt="placeholder"></div><div class="product-details"><h3>'+ product +'</h3><span class="price">$'+ 1 +'</span><div class="actions">Delete<div class="quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="select"><select id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');
var productAdded = $('<li class="product"><div class="product-image"><input type="text" name="item" value="' + item + '" hidden /><input type="text" name="detail" value="' + detail + '" hidden /><img src="/view/images/' + pic + '" alt="placeholder"></div><div class="product-details"><h3>' + product + '</h3><input type="text" name="productname" value="' + product + '" hidden /><input type="text" name="pic" value="/view/images/' + pic + '" hidden /><span class="price">จำนวน</span><span class="price">' + QTY + ' kg.</span><input class="price" type="text" hidden name="QTY" value="' + QTY + '"><div class="actions">ลบ</div></div></li>');
cartList.prepend(productAdded);
}
function removeProduct(product) {
clearInterval(undoTimeoutId);
cartList.find('.deleted').remove();
var topPosition = product.offset().top - cartBody.children('ul').offset().top ,
productQuantity = Number(product.find('.quantity').find('select').val()),
productTotPrice = Number(product.find('.price').text().replace('$', '')) * productQuantity;
product.css('top', topPosition+'px').addClass('deleted');
//update items count + total price
updateCartTotal(1, false);
updateCartCount(true, -productQuantity);
undo.addClass('visible');
//wait 8sec before completely remove the item
undoTimeoutId = setTimeout(function(){
undo.removeClass('visible');
cartList.find('.deleted').remove();
}, 0);
}
function quickUpdateCart() {
var quantity = 0;
var price = 0;
cartList.children('li:not(.deleted)').each(function(){
var singleQuantity = Number($(this).find('select').val());
quantity = quantity + singleQuantity;
price = price + singleQuantity*Number($(this).find('.price').text().replace('$', ''));
});
cartTotal.text(price.toFixed(2));
cartCount.find('li').eq(0).text(quantity);
cartCount.find('li').eq(1).text(quantity+1);
}
function updateCartCount(emptyCart, quantity) {
if( typeof quantity === 'undefined' ) {
var actual = Number(cartCount.find('li').eq(0).text()) + 1 ;
var next = actual + 1;
if( emptyCart ) {
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
} else {
cartCount.addClass('update-count');
setTimeout(function() {
cartCount.find('li').eq(0).text(actual);
}, 150);
setTimeout(function() {
cartCount.removeClass('update-count');
}, 200);
setTimeout(function() {
cartCount.find('li').eq(1).text(next);
}, 230);
}
} else {
var actual = Number(cartCount.find('li').eq(0).text()) -1 ;
var next = actual + 1;
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
}
}
function updateCartTotal(price, bool) {
bool ? cartTotal.text( (Number(cartTotal.text()) + Number(price)).toFixed(0) ) : cartTotal.text( (Number(cartTotal.text()) - Number(price)).toFixed(0) );
}
});
and when i change back to this page it stack a function (one time come back to this page it will do 2 time function and more if you come back again) I must to say sorry my English is not good and so thank you for help.

Jquery custom filters in HTML

I want create a custom filters using jquery.
I started here
var filters = {};
var data = [];
var filters = {};
filters.id = 0;
filters.title = "Users";
data[0] = filters;
var filters = {};
filters.id = 1;
filters.title = "Title";
data[1] = filters;
var filters = {};
filters.id = 2;
filters.title = "Start date";
data[2] = filters;
var filters = {};
filters.id = 3;
filters.title = "End date";
data[3] = filters;
var filters = {};
filters.id = 4;
filters.title = "Price";
data[4] = filters;
var filters = {};
filters.id = 5;
filters.title = "Category";
data[5] = filters;
var i = 0;
$.each(data, function(index, value) {
if (i < 2) {
$(".chooseFilter").append("<option data-filter-id=" + value.id + ">" + value.title + "</option>");
} else {
$(".chooseFilter").append("<option data-filter-id=" + value.id + " disabled>" + value.title + "</option>");
}
i++;
});
var dataHTMLFilters = [];
dataHTMLFilters[0] = '<input class="user" data-filterid="0" type="text" placeholder="Enter username">';
dataHTMLFilters[1] = '<input class="user" data-filterid="1" type="text" placeholder="Enter title">';
dataHTMLFilters[2] = '<input class="user" data-filterid="2" type="text" placeholder="Enter start date">';
dataHTMLFilters[3] = '<input class="user" data-filterid="3" type="text" placeholder="Enter end date">';
dataHTMLFilters[4] = '<input class="user" data-filterid="4" type="text" placeholder="Enter price">';
dataHTMLFilters[5] = '<input class="user" data-filterid="5" type="text" placeholder="Enter category">';
var limits = [];
limits[0] = 5;
limits[1] = 1;
limits[2] = 2;
limits[3] = 3;
limits[4] = 4;
limits[5] = 5;
$("body").on("change", ".chooseFilter", function() {
var filterId = $(this).find(":selected").attr("data-filter-id");
$(this).parent().prev().html(dataHTMLFilters[filterId]);
});
var buttons = '<div><button class="add">add</button><button class="remove">remove</button></div>';
$("body").on("click", ".add", function(e) {
e.preventDefault();
var filterID = $(this).parent().prev().find("option:selected").attr("data-filter-id");
$(".filters").append("<div class='filter'><div>" + $(".chooseFilter")[0].outerHTML + '</div>' + buttons + "</div>");
$(".filter").last().prepend("<div class='sibling'>" + dataHTMLFilters[$(".filter:last-child .chooseFilter option:not(:disabled)").attr("data-filter-id")] + "</div>");
if ($(".chooseFilter option[data-filter-id=" + filterID + "]:selected").length >= limits[filterID]) {
$(".chooseFilter option[data-filter-id=" + filterID + "]").prop("disabled", true);
var filterIdSelected = $(".chooseFilter option:not(:disabled)").first().attr("data-filter-id");
$(".chooseFilter").last().find("option[data-filter-id=" + filterIdSelected + "]").attr("selected", true);
console.log(dataHTMLFilters[filterIdSelected]);
$(".chooseFilter").last().parent().prev().html(dataHTMLFilters[filterIdSelected]);
}
});
$("body").on("click", ".remove", function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter">
<div class="sibling">
<input class="user" data-filterid="0" type="text" placeholder="Enter username">
</div>
<div>
<select class="chooseFilter" style="width: 100%;">
</select>
</div>
<div>
<button class="add ">add</button>
</div>
</div>
</div>
Filters must fulfill,comatibile with:
Take limits to attention in add, remove and change. If limit is equal to instance of length in HTML document filter must be disabled
Basic filters are users, title when filters is only one this two option must be not disabled rest must be disabled when event is add, remove or change
Any ideas how I could do that? I try various method but result always are the same , filters is not compatibile.
If you want some more information how it should work just say.
I see it like this when add,remove and change:
if(users.length >= limit){
//set all option in select where filter is user to disabled = true
}
if(title.length >= limit){
//set all option in select where filter is title to disabled = true
}
if(filters.length > 1){
//options in select set to disable=false
}
if(filters.length < 1){
//options in select set to disable=true and title, users set to false
}

Total required in javascript

I have a query in javascript.. Please check the below image
In Above image :
First Input Box is Description
2nd Input Box is Qty
3rd is Value
I have got total qty using below script onchange of textbox :
function findTotal(){
var total = 0;
var $changeInputs = $('input.qtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
$("#totalvval").val(total);
}
I have got total Value using below :
function qfindTotal(){
var total = 0;
var $changeInputs = $('input.qqtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.qtotal').text(total);
$("#totalqval").val(total);
if(total>10000){
alert("Amount should not be greater than 10000");
}
}
My query is that we need total of qty x value + qty x value + qty x value =total
You can try something like this:
Fiddle
Code
function createHTML() {
var html = "";
for (var i = 0; i < 3; i++) {
html += "<input type='text' class='qty' id='txtQty_" + i + "' onblur='updateTotal()' />";
html += "<input type='text' class='cost' id='txtQty_" + i + "' onblur='updateTotal()'/>";
html += "<br/>"
}
html += "Qty Total: <span id='qty_total'>0</span>";
html += "Cost Total: <span id='cost_total'>0</span>";
document.getElementById("content").innerHTML = html
}
function updateTotal() {
var qty = document.getElementsByClassName("qty");
var cost = document.getElementsByClassName("cost");
var total_qty = 0;
var total_cost = 0;
for (var i = 0; i < qty.length; i++) {
if (qty[i].value && cost[i].value) {
total_cost += qty[i].value * cost[i].value;
total_qty += parseInt(qty[i].value);
}
}
document.getElementById("qty_total").innerHTML = total_qty;
document.getElementById("cost_total").innerHTML = total_cost;
}
(function() {
createHTML();
})()
<div id="content"></div>

javascript value does not add up

I try to make a count up function whenever there is pressed on a button (button is not in this code).
the result of the count up should be in the read only text field.
var html='';
var huidig = 0;
$('body').off('click', '[data-type=product]').on('click', '[data-type=product]', function(e)
{
e.preventDefault();
var price = $(this).attr('data-price');
var name = $(this).attr('data-name');
var id = $(this).attr('data-id');
if($('input[value='+id+']').length > 0)
{
var parent = $('input[value='+id+']').parent();
console.log("parent: " + parent);
var currentValue = parseFloat(parent.find('input[name^=product_amount]').val());
console.log("currentValue: " + currentValue);
currentValue++;
console.log("currentValue: " + currentValue);
parent.find('input[name^=product_amount]').val(parseFloat(currentValue));
console.log(parent.find('input[name^=product_amount]').val(parseFloat(currentValue)));
}
else
{
html+='<div class="row-fluid"><div class="span1"><input type="hidden" name="product[]" value="'+id+'"/><input type="text" readonly="readonly" name="product_amount[]" value="0" /></div> <div class="span7">'+name+'</div> <div class="span3 offset1">€'+price+'</div> </div>';
}
$('.bill').html(html);
amount = amount + parseFloat(price);
$('.total_bill').html(amount.toFixed(2));
});

Categories

Resources