jQuery AJAX 200 Undefined error with multiple / same name attributes[] - javascript

So I am submitting some data which some have the same name="" values like name="product_name[]" etc... which is why i think my current ajax is failing but not sure and not sure how to resolve. Anyone have any ideas? i.e
customer_name:James
customer_address_1:21 Test Road
customer_town:Test town
customer_postcode required:cm16 4rr
customer_email:james#email.com
customer_address_2:other part
customer_county:something
customer_phone:48486486486
customer_name_ship:James
customer_name_2_ship:other part
customer_town_ship:Test town
customer_address_1:21 Test Road
customer_county_ship:something
customer_postcode_ship:cm16 4rr
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:2
invoice_product_price[]:200
invoice_product_discount[]:20%
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:4
invoice_product_price[]:149
invoice_product_discount[]:
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:1
invoice_product_price[]:120
invoice_product_discount[]:40
invoice_subtotal:996.00
invoice_discount:120.00
invoice_shipping:40.00
invoice_vat:199.20
invoice_total:996.00
JSFiddle: http://jsfiddle.net/90jqq4ym/
JS:
$(document).ready(function() {
// add product
$("#action_add_product").click(function(e) {
e.preventDefault();
actionAddProduct();
});
// create invoice
$("#action_create_invoice").click(function(e) {
e.preventDefault();
actionCreateInvoice();
});
// enable date pickers for due date and invoice date
var dateFormat = $(this).attr('data-vat-rate');
$('#invoice_date, #invoice_due_date').datetimepicker({
showClose: false,
format: dateFormat
});
// copy customer details to shipping
$('input.copy-input').on("change keyup paste", function () {
$('input#' + this.id + "_ship").val($(this).val());
});
// remove product row
$('#invoice_table').on('click', ".delete-row", function(e) {
e.preventDefault();
$(this).closest('tr').remove();
calculateTotal();
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function (e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table, #invoice_totals').on('change keyup paste', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
isPercent = $('[name="invoice_product_discount[]"]', tr).val().indexOf('%') > -1,
percent = $.trim($('[name="invoice_product_discount[]"]', tr).val().replace('%', '')),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0) {
if(isPercent){
subtotal = subtotal - ((parseFloat(percent) / 100) * subtotal);
} else {
subtotal = subtotal - parseFloat(percent);
}
} else {
$('[name="invoice_product_discount[]"]', tr).val('');
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal(){
var grandTotal = 0,
disc = 0;
$('#invoice_table tbody tr').each(function() {
var c_sbt = $('.calculate-sub', this).val(),
quantity = $('[name="invoice_product_qty[]"]', this).val(),
price = $('[name="invoice_product_price[]"]', this).val() || 0,
subtotal = parseInt(quantity) * parseFloat(price);
grandTotal += parseFloat(c_sbt);
disc += subtotal - parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal),
vat = parseInt($('.invoice-vat').attr('data-vat-rate')),
c_ship = parseInt($('.calculate.shipping').val()) || 0,
withShip = parseInt(subT + c_ship);
$('.invoice-sub-total').text(subT.toFixed(2));
$('#invoice_subtotal').val(subT.toFixed(2));
$('.invoice-discount').text(disc.toFixed(2));
$('#invoice_discount').val(disc.toFixed(2));
if($('.invoice-vat').attr('data-enable-vat') === '1') {
if($('.invoice-vat').attr('data-vat-method') === '1') {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((withShip).toFixed(2));
$('#invoice_total').val((withShip).toFixed(2));
} else {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((withShip + ((vat / 100) * withShip)).toFixed(2));
$('#invoice_total').val((withShip + ((vat / 100) * withShip)).toFixed(2));
}
} else {
$('.invoice-total').text((withShip).toFixed(2));
$('#invoice_total').val((withShip).toFixed(2));
}
}
function actionAddProduct(){
if($(".required").val() == ''){
$(".required").parent().addClass("has-error");
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
$("#response").fadeIn();
} else {
var $btn = $("#action_add_product").button("loading");
$.ajax({
url: 'response.php',
type: 'POST',
data: $("#add_product").serialize(),
dataType: 'json',
success: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-warning");
$("#response").addClass("alert-success");
$("#response").fadeIn();
$btn.button("reset");
},
error: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response").fadeIn();
$btn.button("reset");
}
});
}
}
function actionCreateInvoice(){
if($(".required").val() == ''){
$(".required").parent().addClass("has-error");
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
$("#response").fadeIn();
} else {
var $btn = $("#action_create_invoice").button("loading");
$.ajax({
url: 'response.php',
type: 'POST',
data: $("#create_invoice").serialize(),
dataType: 'json',
success: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-warning");
$("#response").addClass("alert-success");
$("#response").fadeIn();
$btn.button("reset");
console.log(data);
},
error: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response").fadeIn();
$btn.button("reset");
}
});
}
}
});

Related

Commenting out JS gives dev console error?

I'm trying to comment out a block of code in my site's main.js file, since it makes my sticky header jump in a funny way upon scrolling.
When I comment out the sticky header section, it fixes the jumpy header issue.
However, it also throws the following error in Firefox or Chrome developer console:
Uncaught ReferenceError: jQuery is not defined
Here is the original unedited code:
jQuery(function ($) {
// Sticky Header
if ($('body').hasClass('sticky-header')) {
var header = $('#sp-header');
if($('#sp-header').length) {
var headerHeight = header.outerHeight();
var stickyHeaderTop = header.offset().top;
var stickyHeader = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyHeaderTop) {
header.addClass('header-sticky');
} else {
if (header.hasClass('header-sticky')) {
header.removeClass('header-sticky');
}
}
};
stickyHeader();
$(window).scroll(function () {
stickyHeader();
});
}
if ($('body').hasClass('layout-boxed')) {
var windowWidth = header.parent().outerWidth();
header.css({"max-width": windowWidth, "left": "auto"});
}
}
// go to top
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.sp-scroll-up').fadeIn();
} else {
$('.sp-scroll-up').fadeOut(400);
}
});
$('.sp-scroll-up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// Preloader
$(window).on('load', function () {
$('.sp-preloader').fadeOut(500, function() {
$(this).remove();
});
});
//mega menu
$('.sp-megamenu-wrapper').parent().parent().css('position', 'static').parent().css('position', 'relative');
$('.sp-menu-full').each(function () {
$(this).parent().addClass('menu-justify');
});
// Offcanvs
$('#offcanvas-toggler').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').addClass('offcanvas-active');
});
$('.close-offcanvas, .offcanvas-overlay').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').removeClass('offcanvas-active');
});
$(document).on('click', '.offcanvas-inner .menu-toggler', function(event){
event.preventDefault();
$(this).closest('.menu-parent').toggleClass('menu-parent-open').find('>.menu-child').slideToggle(400);
});
//Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Article Ajax voting
$('.article-ratings .rating-star').on('click', function (event) {
event.preventDefault();
var $parent = $(this).closest('.article-ratings');
var request = {
'option': 'com_ajax',
'template': template,
'action': 'rating',
'rating': $(this).data('number'),
'article_id': $parent.data('id'),
'format': 'json'
};
$.ajax({
type: 'POST',
data: request,
beforeSend: function () {
$parent.find('.fa-spinner').show();
},
success: function (response) {
var data = $.parseJSON(response);
$parent.find('.ratings-count').text(data.message);
$parent.find('.fa-spinner').hide();
if(data.status)
{
$parent.find('.rating-symbol').html(data.ratings)
}
setTimeout(function(){
$parent.find('.ratings-count').text('(' + data.rating_count + ')')
}, 3000);
}
});
});
// Cookie consent
$('.sp-cookie-allow').on('click', function(event) {
event.preventDefault();
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "spcookie_status=ok" + expires + "; path=/";
$(this).closest('.sp-cookie-consent').fadeOut();
});
$(".btn-group label:not(.active)").click(function()
{
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')) {
label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
if (input.val() === '') {
label.addClass('active btn-primary');
} else if (input.val() == 0) {
label.addClass('active btn-danger');
} else {
label.addClass('active btn-success');
}
input.prop('checked', true);
input.trigger('change');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
showCategoryItems( parent, input.val() )
}
});
$(".btn-group input[checked=checked]").each(function()
{
if ($(this).val() == '') {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-primary');
} else if ($(this).val() == 0) {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-danger');
} else {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-success');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
parent.find('*[data-showon]').each( function() {
$(this).hide();
})
}
});
function showCategoryItems(parent, value){
var controlGroup = parent.find('*[data-showon]');
controlGroup.each( function() {
var data = $(this).attr('data-showon')
data = typeof data !== 'undefined' ? JSON.parse( data ) : []
if( data.length > 0 ){
if(typeof data[0].values !== 'undefined' && data[0].values.includes( value )){
$(this).slideDown();
}else{
$(this).hide();
}
}
})
}
$(window).on('scroll', function(){
var scrollBar = $(".sp-reading-progress-bar");
if( scrollBar.length > 0 ){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
const postition = scrollBar.data('position')
if( postition === 'top' ){
// var sticky = $('.header-sticky');
// if( sticky.length > 0 ){
// sticky.css({ top: scrollBar.height() })
// }else{
// sticky.css({ top: 0 })
// }
}
scrollBar.css({width: `${scrollPercent}%` })
}
})
});
The portion I want to comment out is just the "sticky header" block.
I tried to do so like this:
jQuery(function ($) {
// Sticky Header
/* if ($('body').hasClass('sticky-header')) {
var header = $('#sp-header');
if($('#sp-header').length) {
var headerHeight = header.outerHeight();
var stickyHeaderTop = header.offset().top;
var stickyHeader = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyHeaderTop) {
header.addClass('header-sticky');
} else {
if (header.hasClass('header-sticky')) {
header.removeClass('header-sticky');
}
}
};
stickyHeader();
$(window).scroll(function () {
stickyHeader();
});
}
if ($('body').hasClass('layout-boxed')) {
var windowWidth = header.parent().outerWidth();
header.css({"max-width": windowWidth, "left": "auto"});
}
}
*/
// go to top
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.sp-scroll-up').fadeIn();
} else {
$('.sp-scroll-up').fadeOut(400);
}
});
$('.sp-scroll-up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// Preloader
$(window).on('load', function () {
$('.sp-preloader').fadeOut(500, function() {
$(this).remove();
});
});
//mega menu
$('.sp-megamenu-wrapper').parent().parent().css('position', 'static').parent().css('position', 'relative');
$('.sp-menu-full').each(function () {
$(this).parent().addClass('menu-justify');
});
// Offcanvs
$('#offcanvas-toggler').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').addClass('offcanvas-active');
});
$('.close-offcanvas, .offcanvas-overlay').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').removeClass('offcanvas-active');
});
$(document).on('click', '.offcanvas-inner .menu-toggler', function(event){
event.preventDefault();
$(this).closest('.menu-parent').toggleClass('menu-parent-open').find('>.menu-child').slideToggle(400);
});
//Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Article Ajax voting
$('.article-ratings .rating-star').on('click', function (event) {
event.preventDefault();
var $parent = $(this).closest('.article-ratings');
var request = {
'option': 'com_ajax',
'template': template,
'action': 'rating',
'rating': $(this).data('number'),
'article_id': $parent.data('id'),
'format': 'json'
};
$.ajax({
type: 'POST',
data: request,
beforeSend: function () {
$parent.find('.fa-spinner').show();
},
success: function (response) {
var data = $.parseJSON(response);
$parent.find('.ratings-count').text(data.message);
$parent.find('.fa-spinner').hide();
if(data.status)
{
$parent.find('.rating-symbol').html(data.ratings)
}
setTimeout(function(){
$parent.find('.ratings-count').text('(' + data.rating_count + ')')
}, 3000);
}
});
});
// Cookie consent
$('.sp-cookie-allow').on('click', function(event) {
event.preventDefault();
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "spcookie_status=ok" + expires + "; path=/";
$(this).closest('.sp-cookie-consent').fadeOut();
});
$(".btn-group label:not(.active)").click(function()
{
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')) {
label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
if (input.val() === '') {
label.addClass('active btn-primary');
} else if (input.val() == 0) {
label.addClass('active btn-danger');
} else {
label.addClass('active btn-success');
}
input.prop('checked', true);
input.trigger('change');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
showCategoryItems( parent, input.val() )
}
});
$(".btn-group input[checked=checked]").each(function()
{
if ($(this).val() == '') {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-primary');
} else if ($(this).val() == 0) {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-danger');
} else {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-success');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
parent.find('*[data-showon]').each( function() {
$(this).hide();
})
}
});
function showCategoryItems(parent, value){
var controlGroup = parent.find('*[data-showon]');
controlGroup.each( function() {
var data = $(this).attr('data-showon')
data = typeof data !== 'undefined' ? JSON.parse( data ) : []
if( data.length > 0 ){
if(typeof data[0].values !== 'undefined' && data[0].values.includes( value )){
$(this).slideDown();
}else{
$(this).hide();
}
}
})
}
$(window).on('scroll', function(){
var scrollBar = $(".sp-reading-progress-bar");
if( scrollBar.length > 0 ){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
const postition = scrollBar.data('position')
if( postition === 'top' ){
// var sticky = $('.header-sticky');
// if( sticky.length > 0 ){
// sticky.css({ top: scrollBar.height() })
// }else{
// sticky.css({ top: 0 })
// }
}
scrollBar.css({width: `${scrollPercent}%` })
}
})
});
This is effectively commenting out the section and fixing the header bug, but it's also throwing the jQuery not defined error. Is there a more appropriate method for commenting out the section?
Note that the same error occurs if I simply delete the entire sticky header block.
Thank you from a newbie for any help!
Simply try single line comments for each line in the code block. If you have VS Code or similar IDE, then it should do it for you. Select all the lines and press CTRL + / or CMD + / (Mac).
// if ($('body').hasClass('sticky-header')) {
// var header = $('#sp-header');
// if($('#sp-header').length) {
// var headerHeight = header.outerHeight();
// var stickyHeaderTop = header.offset().top;
// var stickyHeader = function () {
// var scrollTop = $(window).scrollTop();
// if (scrollTop > stickyHeaderTop) {
// header.addClass('header-sticky');
// } else {
// if (header.hasClass('header-sticky')) {
// header.removeClass('header-sticky');
// }
// }
// };
// stickyHeader();
// $(window).scroll(function () {
// stickyHeader();
// });
// }
// if ($('body').hasClass('layout-boxed')) {
// var windowWidth = header.parent().outerWidth();
// header.css({"max-width": windowWidth, "left": "auto"});
// }
// }

This my button and function for it. My question is, after click that button.. how to make it disable for 30 mins?

Down there is my button n function for that button in php, how to add disable button for 30 mins after clicking on it? I need help for it because im still newbie on php coding..
<button class="btn btn-primary" style="width: 200px; outline: none;" id="testar" onclick="enviar()">START</button>
This my function:
<script title="ajax do checker">
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
var ap = 0;
var ed = 0;
var rp = 0;
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
var sec = $("#sec").val();
$.ajax({
url: 'g3api.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("Approved")) {
removelinha();
ap++;
aprovadas(resultado + "");
}else if(resultado.match("CCN")) {
removelinha();
ed++;
edrovadas(resultado + "");
}else {
removelinha();
rp++;
reprovadas(resultado + "");
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(ed) + parseInt(rp);
$('#cLive').html(ap);
$('#cWarn').html(ed);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cWarn2').html(ed);
$('#cDie2').html(rp);
}
});
}, 5000 * index);
});
}
function aprovadas(str) {
$(".aprovadas").append(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").append(str + "<br>");
}
function edrovadas(str) {
$(".edrovadas").append(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
function iloveyou(){
alert('PEKPEK')}
</script>
My question is: How to make the button disabled for 30 minutes after it's clicked?
button.addEventListener('click', () => {
if (localStorage.getItem('clicked') === 'true') return;
localStorage.setItem('clicked', 'true');
button.disabled = true;
setTimeout(() => {
localStorage.removeItem('clicked');
button.disabled = false;
}, 60000 * 10);
});

Jquery ui autocomplete with barcode scanner, text is deleted on focusout

I have two input fields that come one after another:
<input class="inputItemNum ui-autocomplete-input" id="tbAutoItemCode1" name="tbAutoItemCode1" type="text" value="" indexer="1" onkeydown="return (event.keyCode!=13);" autocomplete="off">
<input class="inputItemName ui-autocomplete-input" id="tbAutoItemName1" name="tbAutoItemName1" type="text" value="" indexer="1" onkeydown="return (event.keyCode!=13);" autocomplete="off">
The first represents an item code and the other represents an item name.
On both of them I am using jquery-ui autocomplete and in 2 situations:
1) on input
2) on focus out
I need the autocomplete on focusout because I am using an android device with bar-code scanner that inserts two Tab characters as input suffix, so when reading input into the item num it does the autocomplete and when leaving the input element (with one of the tab suffix) it checks if the item num is ok (again with autocomplete - because the user might entered manually an item code that does not exists- in that case I will clean the input fields.)
Also need to mention that my autocomplete list comes from an ajax request.
The problem I am facing is that when reading the item num with the bar-code scanner it also fills in the item name (as expected) but sometimes it deletes the item name the second it was filled.
I thought it was related to the async ajax request (when the response comes back the tab suffix was already inserted and the fields were cleaned) so I tries using the ajax async:false but still no luck there. I hope someone can help me put.
here is my javascript code that uses the autocomplete:
$(document).on('input', '.inputItemNum', function () {
var inputId = $(this).attr("id");
var text = $(this).val();
var index = $(this)[0].attributes["indexer"].value;
if (text.length > 0) {
$(this).autocomplete({
//Alina 22-09-2016 after press a key, it takes 0ms(by default: 300ms) before it re-evaluates the dataset.
delay: 100,
focus: function () {
$(".autoCompleteItemCode").autocomplete("option", "delay", 0);
},
source: function (request, response) {
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: JSON.stringify({ "prefixText": text, "count": 40, 'mode': 'code' }),
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
// console.log(item);
return {
value: item.ItemCode,
code: item.ItemCode,
name: item.ItemName,
price: item.ItemPrice,
multiple: item.Multiple,
vat: item.Vat,
discount: item.Discount
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
},
minLength: 1,
autoFocus: true,
select: function (event, ui) {
$("#tbAutoItemCode" + index).val(ui.item.code);
$("#tbAutoItemName" + index).val(ui.item.name);
$("#tbAutoItemPrice" + index).val(numberToCurrency(ui.item.price));
$("#tbAutoItemMultiple" + index).val(ui.item.multiple);
var l_DiscPrcnt = Math.round(ui.item.discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (ui.item.price * ui.item.multiple) - ((ui.item.price * ui.item.multiple) * (ui.item.discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(ui.item.vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * ui.item.vat / 100);
$("#tbAutoItemComments" + index).click(function () {
//openItemDescription(ui.item.code, ui.item.name)
return false;
});
reCalculateRow(index);
event.preventDefault();
//event.stopPropogation();
//focusQtyColumn(index);
focusItemNameColumn(index);
$(".ui-autocomplete").hide();
//addRow();
return false;
}
});
} // if length > 0
}); //keyup
$(document).on('keydown', '.inputItemNum', function (event) {
var code = event.keyCode || event.which;
if (code == '9') {
//alert("Tab Pressed");
event.stopPropagation();
return;
}
});
$('.inputItemNum').live("focusout", function () {
var index = $(this)[0].attributes["indexer"].value;
if ($(this).val() == "") { return; };
//console.log("Lost focus from indexer " + indexer + " with value " + $(this).val());
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: "{ 'prefixText': '" + $(this).val() + "','count': '1','mode':'exact_code'}", //search for exact code!
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (dataArr) {
if (dataArr.d.length == 0) {
// $("#tbAutoItemCode" + indexer).val("");
clearRowData(index);
reCalculateRow(index);
return;
}
var data = dataArr.d[0];
$("#tbAutoItemCode" + index).val(data.ItemCode);
$("#tbAutoItemName" + index).val(data.ItemName);
$("#tbAutoItemPrice" + index).val(numberToCurrency(data.ItemPrice));
$("#tbAutoItemMultiple" + index).val(data.Multiple);
var l_DiscPrcnt = Math.round(data.Discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (data.ItemPrice * data.Multiple) - ((data.ItemPrice * data.Multiple) * (data.Discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(data.Vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * data.Vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(data.ItemCode, data.ItemName)
return false;
});
reCalculateRow(index);
focusItemNameColumn(index);
//focusQtyColumn(index);
$(".ui-autocomplete").hide();
return false;
}
})
}); //focusout
$(document).on('input', '.inputItemName', function () {
var inputId = $(this).attr("id");
var text = $(this).val();
var index = $(this)[0].attributes["indexer"].value;
if (text.length > 0) {
$(this).autocomplete({
//Alina 22-09-2016 after press a key, it takes 0ms(by default: 300ms) before it re-evaluates the dataset.
delay: 0,
focus: function () {
$(".autoCompleteItemCode").autocomplete("option", "delay", 0);
},
source: function (request, response) {
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: JSON.stringify({ 'prefixText': text, 'count': 40, 'mode': 'name' }),
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
// console.log(item);
return {
value: item.ItemName,
code: item.ItemCode,
name: item.ItemName,
price: item.ItemPrice,
multiple: item.Multiple,
vat: item.Vat,
discount: item.Discount
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
},
minLength: 1,
autoFocus: true,
select: function (event, ui) {
$("#tbAutoItemCode" + index).val(ui.item.code);
$("#tbAutoItemName" + index).val(ui.item.name);
$("#tbAutoItemPrice" + index).val(numberToCurrency(ui.item.price));
$("#tbAutoItemMultiple" + index).val(ui.item.multiple);
var l_DiscPrcnt = Math.round(ui.item.discount * 100) / 100;
$("#discount" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (ui.item.price * ui.item.multiple) - ((ui.item.price * ui.item.multiple) * (ui.item.discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(ui.item.vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * ui.item.vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(ui.item.code, ui.item.name)
return false;
});
reCalculateRow(index);
if(index == $('#orderTable tr:last').index()){
addRow();
}
return false;
}
});
} // if length > 0
}); //keyup
$('.inputItemName').live("focusout", function () {
var index = $(this)[0].attributes["indexer"].value;
var text = $(this).val().trim();
if (text.length == 0) { return };
setTimeout(function(){
//console.log("Lost focus from indexer " + indexer + " with value " + $(this).val());
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: "{ 'prefixText': '" + text + "','count': '1','mode':'name'}", //search for name!
dataType: "json",
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (dataArr) {
if (dataArr.d.length == 0) {
$("#tbAutoItemName" + index).val("");
reCalculateRow(index);
return;
}
var data = dataArr.d[0];
$("#tbAutoItemCode" + index).val(data.ItemCode);
$("#tbAutoItemName" + index).val(data.ItemName);
$("#tbAutoItemPrice" + index).val(numberToCurrency(data.ItemPrice));
$("#tbAutoItemMultiple" + index).val(data.Multiple);
var l_DiscPrcnt = Math.round(data.Discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (data.ItemPrice * data.Multiple) - ((data.ItemPrice * data.Multiple) * (data.Discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(data.Vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * data.Vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(data.ItemCode, data.ItemName)
return false;
});
reCalculateRow(index);
//focusItemNameColumn(index);
//focusQtyColumn(index);
$(".ui-autocomplete").hide();
return false;
}
}) }, 500);
}); //focusout
// for bar-code scanner
$(".inputItemNum").live('click', function () {
$(this).select();
});
$(".inputItemName").live('click', function () {
$(this).select();
});

clearInterval not working | undefined

I have such jQuery code and have problem with clearing intervals.
var secs = 50, width = 100;
var counter = function() {
if(secs > 0) {
secs--;
width = width - 2;
$('#time').css('width', width + '%').attr('aria-valuenow', width);
$('.seconds').html(secs);
} else if(secs == 0){
$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
clearInterval(counter);
setInterval(winner, 3000);
}
};
var winner = function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "game_results"
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "you") {
$('.waiting').addClass('hidden');
$('.you').removeClass('hidden');
} else if (data == "opponent") {
$('.waiting').addClass('hidden');
$('.opponent').removeClass('hidden');
}
}
});
console.log(clearInterval(winner)); // heer
}
function answer(question_id, answer, question) {
var question_higher = question_id + 1;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "play",
answer: answer,
question: question
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "wrong") {
$.playSound('build/sounds/wrong');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-danger');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
} else if (data == "correct") {
$.playSound('build/sounds/correct');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-success');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
}
}
});
if(question_id == 5) {
clearInterval(counter);
setTimeout(function() {
//$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
}, 750);
setInterval(winner, 3000);
}
}
$(document).ready(function() {
$('*[data-question="1"]').removeClass('hidden');
setInterval(counter, 1000);
});
Im trying to get this work for almost 5 hours without results.
Both clearInterval(counter); and clearInterval(winner) are not working and flooding my server with requets.
Thanks in advance for any help.
Let's see how you're clearing the interval.
clearInterval(winner)
where, winner is the function. To clear the interval, the ID of the interval should be passed as parameter.
When setting the interval, catch the interval ID in a variable
winnerInterval = setInterval(winner, 3000);
and use this variable to clear interval.
clearInterval(winnerInterval);
Make sure the variable containing interval ID is in the scope when clearing the interval.
See clearInterval.

Form Validation with sum of fields

I'm trying to get this validation code to work. I only want the user to be able to add to the cart when the sum of the fields is equal to 7, if it does not equal 7 then an error should be shown.
Any help would be great as I can't see where I need to change it.
JSFiddle
$('#button-cart').on('click', function() {
var $fieldsSet = $('div.validateFields');
var MaxSelectionNum = "7"
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$fieldsSet.find('input[name^="option-quantity"]').each(function() {
sum += parseInt($(this).val()) || 0;
});
// Set the sum
$fieldsSet.find('.sum').val(sum);
var allSumEqualCustomDesc = true;
if (allSumEqualCustomDesc) {
$("div.errorQuantity").html("Please select 7 meals").show();
} else {
$("div.errorQuantity").hide();
};
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'number\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
} else {
element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
$('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']);
$('html, body').animate({
scrollTop: 0
}, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
}
);
Here are two ways of doing it:
(Not added the AJAX code but i've commented where it should go)
Example 1:
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").hide();
// AJAX SHOULD GO HERE!
}
});
JSFIDDLE EXAMPLE
Example 2: (Closer to your original code)
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
// Set the sum
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
$(".sum").html(sum);
if ($(document).find('.sum').val(sum) > MaxSelectionNum)
{
$(".errorQuantity").hide();
// AJAX SHOULD GO HERE!
}
else
{
$(".errorQuantity").html("Please select 7 meals").show();
}
});
UPDATED JSFIDDLE
UPDATED (TALKED ABOUT IN COMMENT SECTION):
JSFIDDLE EXAMPLE

Categories

Resources