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.
Related
I'm using a parsley validator and somehow it affects my form. After submission, it won't clear all the inputs; especially hidden inputs. And when I tried to set some input value from javascript it won't show up.
I think it's because of my <form method="post" id="transaction_form">. I've tried to re-evaluate my HTML but still, it won't work properly.
$(document).ready(function () {
$("#cust_num").val(55555);
var exam_num = 12345;
var prod_num = 88998;
var prod_name = "Hello";
var prod_price = 150000;
var transactionTable = $("#transaction_table");
var trxprodcount = 0;
var subTotal = 0;
var endTotal = 0;
function clearinput() {
$("#transaction_form")[0].reset();
$("#transaction_form").parsley().reset();
//$('#get_productdata').attr('disabled', 'disabled');
$("#subtotal").html(0);
$("#endtotal").html(0);
}
clearinput();
function recount() {
subTotal = transactionTable.DataTable().column(3).data().sum();
$("#subtotal").html(subTotal);
endTotal = subTotal - (subTotal * $("#trx_disc").val()) / 100;
$("#endtotal").html(endTotal);
}
transactionTable.DataTable({
ordering: false,
responsive: true,
searching: false,
paging: false,
info: false,
fnRender: function (Obj) {
return "Rp" + Obj.Data[3];
},
drawCallback: function () {
recount();
},
});
$("#trx_disc").on("change", function () {
recount();
});
trxprodcount = trxprodcount + 1;
var exam_num = $("#cust_num").val() + "S" + trxprodcount;
var col_exam_num =
exam_num +
'<input type="hidden" name="hidden_exam_num[]" id="exam_num' +
trxprodcount +
'" class="exam_num" value="' +
exam_num +
'" />';
var col_exam_prod =
prod_num +
'<input type="hidden" name="hidden_exam_prod[]" id="exam_prod' +
trxprodcount +
'" value="' +
prod_num +
'" />';
var del_btn =
'<button type="button" name="del_prodtrx" id="' +
trxprodcount +
'" class="btn btn-danger btn-sm del_prodtrx" >Delete</button>';
transactionTable
.DataTable()
.row.add([col_exam_num, col_exam_prod, prod_name, prod_price, del_btn])
.draw()
.node();
$("#transaction_table").on("click", ".del_prodtrx", function () {
var row = $(this).parents("tr");
if ($(row).hasClass("child")) {
transactionTable.DataTable().row($(row).prev("tr")).remove().draw();
} else {
transactionTable.DataTable().row($(this).parents("tr")).remove().draw();
}
});
$("#transaction_form").on("submit", function (event) {
event.preventDefault();
if ($("#transaction_form").parsley().isValid()) {
var count_data = 0;
$(".exam_num").each(function () {
count_data = count_data + 1;
});
if (count_data > 0) {
clearinput();
} else {
$("#message").html(
'<div class="alert alert-danger">Customer/Product Kosong'
);
}
setTimeout(function () {
$("#message").html("");
}, 3000);
}
});
});
Live Example: https://jsfiddle.net/azissofyanp/9p7j1d6u/30/
And I'm very confused about it.
My first pop up list distinct customers with distinct cust_id from the AJAX call. I'm trying to get the count of the number of rows with cust_id that are the same as the selected customer.
For example: If I select "Jeffs Music" from the distinct list I need the count to return 5 since there are 5 rows that cust_id = "15"
$('.add-invoice').live('click', function() {
$("#invoice_div").css("display", "block");
$.ajax({
url: 'invoice_fill.php',
data: {
action: "invoice"
},
dataType: 'json',
success: function(data) {
var result = [];
$.each(data, function(i, e) {
var matchingItems = $.grep(result, function(item) {
return item.customer === e.customer && item.cust_id === e.cust_id;
console.log(item.cust_id);
});
if (matchingItems.length === 0) {
result.push(e);
}
});
var xyz = (JSON.stringify(result));
console.log(xyz);
populateSelectBoxes($('#invoice_div #ddinvoice'), result);
function populateSelectBoxes($select, result) {
var invoices = [];
$.each(result, function() {
invoices.push('<li data-value="' + this.cust_id + '">' + this.customer + ' : ' + this.invoice + '</li>');
});
$select.append(invoices.join(''));
}
function populateTableRow(data, selectedProductAutonum) {
var invoices;
$.each(result, function() {
if (this.cust_id == selectedProductAutonum) {
invoices = this;
var arr = this.cust_id;
var occurrences = {};
for (var i = 0, j = arr.length; i < j; i++) {
occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}
console.log(occurrences);
return false;
// changed autonun to cust_id to give unique record/product call (changed in line 248 as well)
}
});
$(".item-row:last").after(
'<tr class="item-row"><td class="item-name"><div class="delete-wpr"><textarea form ="testinsert" name="item_name[]">Item Name</textarea><a class="delete" href="javascript:;" title="Remove row">X</a><a class="add-product" href="javascript:;" title="Add Product">A</a></div></td><td class="description"><textarea form ="testinsert" name="item_desc[]">Description</textarea></td><td><textarea class="cost" form ="testinsert" name="item_cost[]">$0</textarea></td><td><textarea class="qty" form ="testinsert" name="item_qty[]">0</textarea></td><td><span class="price" form ="testinsert" name="item_price[]">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
$('#address-title').val(invoices.customer);
$('#address-one').val(invoices.address);
//$('#address-two').val(invoices.sales + '\n' + invoices.owed);
//$('#address-three').val(invoices.address3);
///////////////////////////////////////////
$('#invoice_num').val(invoices.invoice);
$('#paid').val(invoices.paid);
$('#owed').val(invoices.sales);
$('#auto_num').val(invoices.autonum);
///////////////////////////////////////////
$('[name="item_name[]"]').val(invoices.product);
$('[name="item_desc[]"]').val(invoices.description);
$('[name="item_cost[]"]').val(invoices.cost);
$('[name="item_qty[]"]').val(invoices.quantity);
$('[name="item_price[]"]').val(invoices.price);
}
$('#invoice_div #ddinvoice li').click(function(e) {
var selection = $(this).attr("data-value");
$(this).parent().parent().parent().hide();
populateTableRow(data, selection);
$('ul').empty();
});
}
});
update_total();
});
Look at this jsFiddle for full code. That should be clear, however the AJAX calls are not working in it?
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);
I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.
here is my script:
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
})
this is what i use to select:
$(':button.diaries').click(function(){});
but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?
#Kelvin Aliyanto ....So the solution will be like this
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
});
$('div').on('click', '.diaries', function(event){
alert("Hi");
}) ;
});
</script>
<div id="diaryList"></div>
check your code is after document ready
$(document).ready(function(){ //your code here });
and use
$('button.diaries').on(click , function(){})
instead of .click
I'm using a plugin to duplicate textfields on add and remove buttons. Now, after getting the fields added and removed, I want to form JSON out of all the textfields and POST it on submit.
Below is the code -
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
JSFiddle can be referred to.
I want to get the values of all textfields and form JSON.
Iterate through the input fields, grab their values, and push them through JSON.stringify to create your desired JSON.
function serializeAndPost() {
var values = [];
$( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
values.push( element.value );
} );
var json = JSON.stringify( { "welcomesList": values } );
// Do your POSTing here
}
Updated fiddle:
https://jsfiddle.net/tZPg4/11019/
I don't know if this is the best solution as I am building a string rather than an JSON object but here is my solution:
HTML
<input type="button" id="btnSubmit" value="Submit"></input>
JS:
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('#btnSubmit').click(function(e) {
e.preventDefault();
var str = [];
$.each($('input[type=text]'), function(i, val) {
var el = $(this);
str.push('"' + el.attr("id") + '":"' + el.val() +'"');
});
var json_string = "{" + str + "}";
});
});