Refresh part of page when user navigated back to it - javascript

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>

Related

Have two variables in one foreach bad insert

Hello i have a trouble with my code.
I have HTML with JS:
$(document).ready(function () {
// allowed maximum input fields
var max_input = 5;
// initialize the counter for textbox
var x = 1;
// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
Remove
</div>
`); // add input field
}
});
// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
x--; // decrement the counter
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>
and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.
php script:
This is a function and $id_produkt is GET from url.
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){
$input_name = $_POST["input_name"];
$input_price = $_POST["input_price"];
foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);
$result = db_query($sql, $data);
return $result;
}
}
Can help me please ? I am tired
I make function like that and working.
function insertVariantsProduct($id_produkt){
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) {
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {
$var_id = $_POST["input_id"][$i];
$name = $_POST["input_name"][$i];
$price = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id' ";
$data = null;
}
$result = db_query($sql, $data);
}
}
return $result; // This should be out of loop because it's will break the loop
}
}

Submit span content to a database

Just for fun, I'm trying to build a simple time tracker; the page grabs a stored duration from a database, and you can then add more time to that value, and then store it back to the database.
The value is displayed in h:i:s format, but there's also a hidden span with the same time but just in seconds.
My problem:
I cannot figure out how to submit the contents of the span to the database.
If I instead put the hidden span contents inside a form input, then the content doesn't change; it just submits the original value back to the database.
I really feel like I'm making a bit of a meal out of this.
Here's the current code...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
//wip - for later - and remember to remove the injection!!!
if(sizeof($_POST) != 0){
$query = "UPDATE my_table SET t=SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$pdo->query($query);
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<div>
<div>
<span hidden id="tts"><?php echo $tts; ?></span>
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").text(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.querySelectorAll('div').forEach(div => {
div.querySelectorAll('span')
.forEach(span => console.log(span.textContent));
});
}
</script>
With CBroe's useful hint, the following works... although my attempts at preparing and binding $_GET are failing at the moment, so the query itself remains insecure...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
if(sizeof($_GET) != 0){
$query = "UPDATE my_table SET t = SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<form id="myForm">
<input name="tts" type= "hidden" id="tts" value="tts">
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").val(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
}
</script>

Woocommerce | Plus Minus remove negative numbers (min_value)

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);
.....

POST Json to PHP get VAR

i have a form like this:
<?php
include '../db/baza.php';
?>
<?php include 'vrh.php' ?>
<div id="stranica">
<div id="stranicaOkvir">
<form action="dodaj_sliku_obrada.php" method="POST" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Dodaj sliku</legend>
<?php $upit = "SELECT kategorija_ID, kategorija_naziv FROM kategorije ORDER BY kategorija_ID ASC";
$ispis = mysql_query($upit) or die(mysql_error());
$blok_ispis = mysql_fetch_assoc($ispis);
$ukupno = mysql_num_rows($ispis); ?>
<p><strong>Obavezno odaberite kategoriju kojoj slika pripada</strong></p>
<p> <select name="kategorija" id="kategorija">
<?php do { ?>
<option value="<?php echo $blok_ispis['kategorija_ID']; ?>"> <?php echo $blok_ispis['kategorija_naziv']; ?></option>
<?php } while ($blok_ispis = mysql_fetch_assoc($ispis)); ?>
<?php mysql_free_result($ispis);?>
</select>
</p>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Dodaj sliku">
<div class="progresbar">
<span class="progresbar-puni" id="pb"><span class="progresbar-puni-tekst" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will apper here.
<script src="js/dodaj_Sliku.js"></script>
<script>
document.getElementById('submit').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'dodaj_sliku_obrada.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
uspjesno_Dodano = document.createElement('div'),
neuspjelo_Dodavanje = document.createElement('div'),
anchor,
span,
x;
if(data.neuspjelo_Dodavanje.length){
neuspjelo_Dodavanje.innerHTML = '<p>Nazalost, sljedece nije dodano: </p>';
}
uploads.innerText = '';
uploads.textContent = '';
for( x = 0; x < data.uspjesno_Dodano.length; x = x + 1){
anchor = document.createElement('a');
anchor.href = '../slike/galerija/' + data.uspjesno_Dodano[x].file;
anchor.innerText = data.uspjesno_Dodano[x].name;
anchor.textContent = data.uspjesno_Dodano[x].name;
anchor.target = '_blank';
uspjesno_Dodano.appendChild(anchor);
}
for( x = 0; x < data.neuspjelo_Dodavanje.length; x = x + 1){
span = document.createElement('span');
span.innerText = data.neuspjelo_Dodavanje[x].name;
span.textContent = data.neuspjelo_Dodavanje[x].name;
neuspjelo_Dodavanje.appendChild(span);
}
uploads.appendChild(uspjesno_Dodano);
uploads.appendChild(neuspjelo_Dodavanje);
},
error: function(){
console.log('Ne radi!');
}
});
});
</script>
<script>
</script>
</div>
</fieldset>
</form>
</div>
</div>
<?php include 'dno.php' ?>
The .js looks like this
var app = app || {};
(function(o){
"use strict";
//Privatne metode
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uspjesno_Dodano;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4){
if(this.status === 200){
uspjesno_Dodano = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uspjesno_Dodano);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if(event.lengthComputable === true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1){
data.append('file[]', source[i]);
}
data.append('ajax', true);
data.append('kategorija', o.options.kategorija);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText = value ? value + '%' : '';
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
ajax(getFormData(o.options.files.files));
}
}
}(app));
On the process.php part i want to listen the option value from select
"<select name="kategorija" id="kategorija">"
on the process.php when i
<?php
$kategorija = $_POST['kategorija'];
echo echo $kategorija;
?>
i alwasy get a 0 value, so what i am doing wrong? The file[] processing is working fine, but can't get it to work with a addtional variable.
You don't need to echo echo $kategorija; It should be echo $kategorija; If this causes an issue, which it might, try var_dump($kategorija) to view the contents of the variable.
Also, you're including your js throughout the page, this should be refactored and included properly in the head. The php should not be in the form of the document, it should be contained outside and included like you are doing with '../db/baza.php'; Finally, look into using PDO to connect to your db.

javascript for loop in codeigniter

Here's my view :
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
var batas = $('#bts'+i).val();console.log(batas);
}
});
<input type="hidden" id="<?php echo 'edge'.$items['id']?>" value="<?php echo $items['options']['jum']?>"/>
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i< $length; $i++) {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
?>
$items['options']['jum'] contains = 2.
$stok['stokbagus'] contains = 30 and 21.
It'll display the first one (30). How to display all $stok['stokbagus'] in javascript?
Because i want to compare $(".qty").val() with all of $stok['stokbagus']
Okay. Here is what you should do.
If your $stok['stokbagus'] variable is array, then you should select the first and the second variable like this:
$first = $stok['stokbagus'][0];
$second = $stok['stokbagus'][1];
Else if, your $stok['stokbagus'] variable is a string and has 30,21 like this;
$vars = explode(",", $stok['stokbagus']);
$first = $vars[0];
$second = $vars[0];
You are saying that $stok['stokbagus'] variable has 30 and 21 values then it must be an array.
To show all values in your $stok['stokbagus'];
implode(', ', $stok['stokbagus']; // or just use $er.
Full:
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.implode(', ', $er).'"/>';
Update:
<?php
foreach ($items['options']['stok'] as $stok) {
$er = $stok['stokbagus'];
$length = $items['options']['jum'];
for ($i=1; $i < $length; $i++) {
if(is_array($er)) {
foreach($er as $key => $value) {
echo '<input type="text" rel="'.$items['rowid'].'" class="bts" data-id="'.$i.'" value="'.$value.'"/>';
}
} else {
echo '<input type="text" rel="'.$items['rowid'].'" id="bts'.$i.'" value="'.$er.'"/>';
}
}
}
Js:
$(".qty").keyup(function(){
var qty = $(this).val();
var bt = (this.id);
var bts = $('#bts'+bt).val();
var edge = $('#edge'+bt).val();
for (var i = 1; i<edge; ++i) {
// I don't know what do you want to do with batas variable...
if($('.bts').length > 1) {
$('.bts').each(function(){
console.log($(this).val());
});
} else {
var batas = $('#bts'+i).val();console.log(batas);
}
}
});

Categories