The problem in question is not to allow me to click on a checkbox if the atendimento number (atendimento.value) is different from a previously entered number.
When I first click on 1 checkbox I store this value and a push to an array.
If I click on another checkbox and the atendimento.value is different, it will display the error message with toast.
I would like to know what I'm forgetting / missing in my code.
ng.checkAtendimento = function(id) {
var atendimento = document.getElementById('atendimento-' + id);
var checkOs = document.getElementById('checkOs-' + id);
var array = [];
if(checkOs.checked){
array.push(atendimento.value);
console.log(array);
}else{
var index = array.indexOf(atendimento.value);
array.splice(index, 1);
console.log(array);
}
if(array[0] != atendimento.value){
console.log(array[0]);
toastr.error(
'error',
'service', {
closeButton: true,
progressBar: true,
timeOut: 7000
});
checkOs.checked = false;
}
}
HTML/PHP
<input id="checkOs-<?php echo $entity->getId(); ?>"
ng-click="checkAtendimento('<?php echo $entity->getId(); ?>');"
type="checkbox"
class="array-ordemservico"
name="[]array-ordemservico"
value="<?php echo $entity->getId();?>" />
<input id="atendimento-<?php echo $entity->getId(); ?>"
class="array-atendimento"
style="display:none" type="checkbox"
value="<?php echo $entity->getAtendimento(); ?>" />
ng.checkAtendimento = function(id){
var atendimento = document.getElementById('atendimento-' + id);
$("#checkOs-" + id).on("change", function (){
index = $.inArray(atendimento.value, ArrayCheckbox);
if ($("#checkOs-" + id).prop('checked')){
if (ArrayCheckbox.length > 0 && index === -1 && atendimento.value != ""){
toastr.error(
'error',
'OS',{
closeButton: true,
progressBar: true,
timeOut: 7000
});
$("#checkOs-" + id).prop("checked", false);
} else if(ArrayCheckbox.length == 0 && atendimento.value != ""){
ArrayCheckbox.push(atendimento.value);
}
} else if((ArrayCheckbox[0] == atendimento.value)){
ArrayCheckbox.splice(index, 1);
}
});
}
Related
In my shop page, for each product I have cart quantities that the user can change without add to cart button (it's with display none and activated by js).
my problem is that if a user changed item quantity in single product page and navigated back into shop page it show the wrong quantity from cache.
Right now i'm reloadin the whole page using this code:
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
var isquanpage = document.getElementsByClassName('store-quantity');
if (isquanpage.length > 0) {
console.log(isquanpage);
$("#a2cloader").show();
location.reload(true);
document.addEventListener('DOMContentLoaded', function() {
$("#a2cloader").hide();
}, false);
}
}
});
});
I want to refresh just the quantities and not the whole page:
<div class="quantity-div" >
<i class="fas fa-plus sumsum-quantity-b" value="+" onclick="store_quantity_b('+', this.parentNode.querySelector('input[type=number]').id);"></i>
<input class="sumsum-quantity store-quantity" form="<?php echo $product->id; ?>" inputmode="decimal" style="padding:0;border-radius:5px;" type="number" min="0" value="<?php echo $cartquan ?>"
name="<?php echo $varid; ?>" onclick="this.select()" id="quantity-<?php echo $varid ?>" data-cartquan="<?php echo $cartquan ?>" data-varititle="<?php echo get_the_title( $attribute_value['variation_id']); ?>">
<i class="fas fa-minus sumsum-quantity-b" value="-" onclick="store_quantity_b('-', this.parentNode.querySelector('input[type=number]').id);"></i>
</div>
And what i tried to do is this:
quanfield = document.getElementsByClassName("store-quantity");
cartquantities =<?php echo json_encode(WC()->cart->get_cart_item_quantities();); ?>;
console.log(cartquantities);
But it gets the cached version of the cart and not the updated one.
OK, i found a solution, I'm using hook on woocommerce add to cart fragments like this:
// cart quantities
add_filter( 'woocommerce_add_to_cart_fragments', woocommerce_cartquant_fragment' );
function woocommerce_cartquant_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<p id="cartquantities" style="display:none"><?php echo json_encode(WC()->cart->get_cart_item_quantities()); ?></p>
<?php
$fragments['p#cartquantities'] = ob_get_clean();
return $fragments;
}
and then using this script:
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj;
let findname =[];
$("#a2cloader").show();
timeout = setTimeout(function() {
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
}, 1500 );
}
});
});
Is there a possibility to make javascript wait for the fragments instead of setting timeout?
SOLVED! used interval to check when fragments are updated
<script>
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj,timer;
let findname =[];
$("#a2cloader").show();
//var t=0;
timer = setInterval(checkfrags, 5);
function checkfrags(){
//t+=5;
if(document.getElementById("cartquantities").innerText=="null") {
//console.log(t);
}else{
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
//console.log(document.getElementById("cartquantities").innerText+"done "+t);
document.getElementById("cartquantities").innerText="null";
clearInterval(timer);
}
}
}
});
});
</script>
<p id="cartquantities" style="display:none">null</p>
I ask you for help please, I haven't come out of it for hours.
I set the quantity selector on the Woocommerce shop page,
which automatically puts the item in the cart and / or removes it.
I have a big problem, when I am on zero and I press - the numbers go negative, I would make sure that it cannot go below zero.
Thanks so much!!
Function.php
// Remove Add To cart Button
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
// Add our Quanity Input
add_action('woocommerce_after_shop_loop_item', 'QTY');
function QTY()
{
global $product;
?>
<div class="shopAddToCart">
<button value="-" class="minus2" >-</button>
<input type="text"
disabled="disabled"
size="2"
value="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
id="count"
data-product-id= "<?php echo $product->get_id() ?>"
data-in-cart="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['in_cart'] : 0;
?>"
data-in-cart-qty="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
class="quantity qty qty-botton"
max_value = "<?php echo ($product->get_max_purchase_quantity() == -1) ? 1000 : $product->get_max_purchase_quantity(); ?>"
min_value = <?php echo $product->get_min_purchase_quantity(); ?>
>
<button type="button" value="+" class="plus2" >+</button>
</div>
<?php
}
//Check if Product in Cart Already
function Check_if_product_in_cart($product_ids)
{
foreach (WC()->cart->get_cart() as $cart_item):
$items_id = $cart_item['product_id'];
$QTY = $cart_item['quantity'];
// for a unique product ID (integer or string value)
if ($product_ids == $items_id):
return ['in_cart' => true, 'QTY' => $QTY];
endif;
endforeach;
}
//Add Event Handler To update QTY
add_action('wc_ajax_update_qty', 'update_qty');
function update_qty()
{
ob_start();
$product_id = absint($_POST['product_id']);
$product = wc_get_product($product_id);
$quantity = $_POST['quantity'];
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item):
if ($cart_item['product_id'] == $product_id) {
WC()->cart->set_quantity($cart_item_key, $quantity, true);
}
endforeach;
wp_send_json('done');
}
*.js jQuery on Footer
jQuery(document).ready(function ($) {
"use strict";
// Add Event Listner on the Plush button
$('.plus2').click(function () {
if (parseInt($(this).prev().val()) < parseInt($(this).prev().attr('max_value'))) {
$(this).prev().val(+$(this).prev().val() + 1);
var currentqty = parseInt($(this).prev().attr('data-in-cart-qty')) + 1;
var id = $(this).prev().attr('data-product-id');
var data = {
product_id: id,
quantity: 1
};
$(this).prev().attr('data-in-cart-qty', currentqty);
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
}
});
$('.minus2').click(function () {
$(this).next().val(+$(this).next().val() - 1);
var currentqty = parseInt($(this).next().val());
var id = $(this).next().attr('data-product-id');
var data = {
product_id: id,
quantity: currentqty
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'update_qty'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
});
});
Just add a check before running the line:
$(this).next().val(+$(this).next().val() - 1);
that will become:
if ( $(this).next().val() > 0 ) {
$(this).next().val(+$(this).next().val() - 1);
}
Also note that you are using an identical id for each quantity input of each product. The id attribute value should be unique on the page.
Here you can find some methods of adding plus and minus buttons in the quantity field of the add to cart form (which you could take inspiration from):
Custom plus and minus quantity buttons in Woocommerce 3
WooCommerce plus and minus buttons
WooCommerce: Add to Cart Plus & Minus Buttons
Thanks Vincenzo Di Gaetano.
I solved it like this:
$('.minus2').click(function () {
var $minus2 = $(this);
var oldValue = $minus2.parent().find("input").val();
if (oldValue > 0) {
$(this).next().val(+$(this).next().val() - 1);
.....
I have a php project that inserts the coordinates of the selected seats of a theater in a db msql.
This is the js file that draws the map and contains the variables.
var price = 0; //price
var $cart = $('#selected-seats'); //Sitting Area
var $counter = $('#counter'); //Votes
var $total = $('#total'); //Total money
var sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaa__a',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaabbb'
],
naming : {
top : true,
rows: ['A','B','C','D','E'],
getLabel : function (character, row, column) {
return column;
}
},
seats:{
a:{
price: 99.9
},
b:{
price: 200
}
},
legend : { //Definition legend
node : $('#legend'),
items : [
[ 'a', 'available', 'Option' ],
[ 'a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
var maxSeats = 3;
var ms = sc.find('selected').length;
//alert(ms);
if (ms < maxSeats) {
price = this.settings.data.price;
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+'</option>')
.attr('id', 'cart-item-'+this.settings.id)
.attr('value', this.settings.id)
.attr('alt', price)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
$counter.attr('value', sc.find('selected').length+1);
$total.text(recalculateTotal(sc));
$total.attr('value', recalculateTotal(sc));
return 'selected';
}
alert('You can only choose '+ maxSeats + ' seats.');
return 'available';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length-1);
$counter.attr('value', sc.find('selected').length-1);
//Delete reservation
$('#cart-item-'+this.settings.id).remove();
//update totalnum
$total.text(recalculateTotal(sc));
$total.attr('value', recalculateTotal(sc));
//Delete reservation
//$('#cart-item-'+this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-line camelcase
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
// #todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
// Add total money
function recalculateTotal(sc) {
var total = 0;
$('#selected-seats').find('option:selected').each(function () {
total += Number($(this).attr('alt'));
});
return number_format(total,2,'.','');
}
This file is viewed by a PHP file in a form like this
<div class="demo" style="margin-top:10px;min-width: 360px;">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div id="legend"></div>
</div>
<form role="form" id="myfrm2" action="book.php?id=<?php echo $FILM_ID; ?>" method="post">
<input type="hidden" name="session" value="<?php echo $session; ?>">
<input type="hidden" name="date" value="<?php echo $date; ?>">
<select class="form-control" style="display:block;" id="selected-seats" name="seat[]" multiple="multiple"></select>
<p>Tickets: <input id="counter" name="counter" readonly></input></p>
<p>Total: <b>€<input id="total" name="total" readonly></input></b></p>
<button type="submit" style="display: block; width: 100%;" name="book" value="book" class="btn btn-danger">Book</button>
</form>
<?php } ?>
</div>
All data are inserted into a DB mysql by this PHP file
<?php
if (isset($_POST['book'])) {
$date = $_POST["date"];
$session = $_POST["session"];
$counter = $_POST["counter"];
$total = $_POST["total"];
$user_id = $_SESSION["id"];
$film_id = $_GET['id'];
$seat = (isset($_POST['seat']) ? $_POST['seat']:array());
if (is_array($seat)) {
foreach ($seat as $selectedOption){
$query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, BOOKING_PRICE, BOOKING_NUM)
VALUES ('$user_id','$film_id','$session','$date','$selectedOption','$total','$counter')";
$result = mysqli_query ($connection,$query)
or die ("<div class='alert alert-danger' role='alert'>You couldn't execute query</div>");
}
echo " <div class='alert alert-success' role='success'>
Congrats your booking has been done! Print the tickets <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
</div>";
}
}
?>
Everything works correctly, all data are inserted in the DB !
But I have added a data to insert to the DB, the price SEAT_PRICE, so I have changed the "option selected" in the JS file to this
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+' P'+this.settings.data.price+'</option>')
the price (the tag in the console is "alt" is now visible on the page but I don't understand how to store this data to the DB.
Any suggestion is appreciated
OK after many attempts and posts in many forum, I have found my solution.
1) The JS file must be modified like that (passing 2 values):
$('<option selected>R'+(this.settings.row+1)+' S'+this.settings.label+' P'+this.settings.data.price+'</option>')
.attr('id', 'cart-item-'+this.settings.id)
.attr('value', this.settings.id + "|" + this.settings.data.price)
.attr('alt', price)
.data('seatId', this.settings.id)
.appendTo($cart);
2) the PHP file must be changed like that (dividing seat array - separated by "|" - to post the 2 values:
<?php
if (isset($_POST['book'])) {
$date = $_POST["date"];
$session = $_POST["session"];
$counter = $_POST["counter"];
$total = $_POST["total"];
$user_id = $_SESSION["id"];
$film_id = $_GET['id'];
$seat = (isset($_POST['seat']) ? $_POST['seat']:array());
if (is_array($seat)) {
foreach ($seat as $selectedOption){
$ar = explode('|',$selectedOption);
$query = "INSERT INTO booking(USER_ID, FILM_ID, BOOKING_SESSION, BOOKING_DATE, BOOKING_SEAT, SEAT_PRICE, BOOKING_PRICE, BOOKING_NUM)
VALUES ('$user_id','$film_id','$session','$date','$ar[0]','$ar[1]','$total','$counter')";
$result = mysqli_query ($connection,$query)
or die ("<div class='alert alert-danger' role='alert'>You couldn't execute query</div>");
}
echo " <div class='alert alert-success' role='success'>
Congrats your booking has been done! Print the tickets <a href='./fpdf18/generate-pdf.php?film=$film_id' target='_blank'>here</a>!
</div>";
}
}
?>
I want a jquery condition which will handle the following scenarios -
1) Some of the checkboxes selected
2) All of the checkboxes selected
I want them both in a single loop. Currently, I've the following code to select all checkboxes only -
$('.check-all').click(function() {
var selector = $(this).is(':checked') ? ':not(:checked)' : ':checked';
var ids = [];
$('#chkall input[type="checkbox"]' + selector).each(function() {
$(this).trigger('click');
ids.push($(this).attr('value'));
});
var id = [];
id = JSON.stringify(ids);
document.cookie = "ids="+id;
});
And taking checkboxes in my PHP code as -
echo '<ul class="list-unstyled" id="chkall">';
foreach ($contacts as $contact) {
echo '<li>
<div class="checkbox" id="checkboxes">
<label><input type="checkbox" class="case" name="case" value="'.$contact['cust_id'].'" id="'.$contact['cust_id'].'">'.$contact['cust_fname'].' '.$contact['cust_lname'].'</label>
</div>
</li>';
}
So, how should I handle both scenarios in a single loop ? I've send a cookie when checking is done.
I found a solution & now doing this in a following way -
PHP Code -
echo '<ul class="list-unstyled" id="chkall">';
foreach ($contacts as $contact) {
echo '<li>
<div class="checkbox" id="checkboxes" onclick="getID('.$contact['cust_id'].')">
<label><input type="checkbox" class="check-all" name="case" value="'.$contact['cust_id'].'" id="'.$contact['cust_id'].'">'.$contact['cust_fname'].' '.$contact['cust_lname'].'</label>
</div>
</li>';
}
<div class="checkbox" onclick="getID('0')">
<?= Html::checkbox(null, false, [
'id' => 'selectall',
'label' => 'Select all',
'class' => 'check-all',
]);?>
</div>
</div>
And the respective script is -
var ids = [];
function getID(id) {
var checkboxlist = document.getElementsByName('case');
var itr = 0, checkedFlag = 0, uncheckedFlag = 0;
var inputElements = document.getElementsByClassName('check-all');
if (id == 0) {
$(".check-all").prop("checked", $("#selectall").prop("checked"))
}
else {
for (var i = 0; inputElements[i]; ++i) {
if (inputElements[i].value == id) {
if (inputElements[i].checked == true) {
inputElements[i].checked = false;
break;
}
else {
inputElements[i].checked = true;
break;
}
}
}
while (itr < checkboxlist.length) {
if (checkboxlist[itr].checked == true) {
checkedFlag++;
}
else {
$("#selectall").prop("indeterminate", true);
uncheckedFlag++;
}
itr++;
}
if (checkedFlag == checkboxlist.length) {
$("#selectall").prop("indeterminate", false);
$("#selectall").prop("checked", true);
}
if (uncheckedFlag == checkboxlist.length) {
$("#selectall").prop("indeterminate", false);
$("#selectall").prop("checked", false);
}
}
}
That's it !!!
I have this ajax code:
<script>
$(document).ready(function() {
$('ul#tab li:first').html('<?php echo $channel;?>');
$('ul#tabs li').on("click", function() {
// $('ul#tab li.active').html($(this).html());
$('ul#tab li').html("");
//$('ul#tab li.active').html($(this).html());
var index = $("ul#tabs li").index($(this));
$.post("../admin/ajax/ch1.php", {
index: index
}, function(result) {
$('ul#tab li.active').html(result);
});
});
});
</script>
and in the php ch1.php is
<?php
$ch1tab1= file_get_contents("../channels/ch1tab1.html");
$ch1tab2= file_get_contents("../channels/ch1tab2.html");
$ch1tab3= file_get_contents("../channels/ch1tab3.html");
$ch1tab4= file_get_contents("../channels/ch1tab4.html");
$ch1tab5= file_get_contents("../channels/ch1tab5.html");
$channel = $_POST['index'];
if ($_POST['index'] == 0 ){ $channel = $ch1tab1;}
else if ($_POST['index'] == 1){ $channel = $ch1tab2;}
else if ($_POST['index'] == 2 ){ $channel= $ch1tab3;}
else if ($_POST['index'] == 3 ) {$channel = $ch1tab4;}
else if ($_POST['index'] == 4 ) {$channel = $ch1tab5;}
echo $channel; ?>
the varible ch1tab4 have a code , and it is not work , echo blank
what i should to do plz ?
Why don't you use jQuery's .load() function? It uses the following syntax:
$(selector).load(URL,data,callback);