Reputation: 65
I am trying to have a piece of code that displays data from table, saves the data inside a checkbox which, if selected, posts it forward. But I am stuck on a problem with trying to select a different amount of quantity than the original, it will always select the maximum amount due to the checkbox being set to stone when the page is loaded, can I update the checkbox values in some way? The checkbox code looks like this:
$order = wc_get_order( $ordernumber );
foreach ($order->get_items() as $item ){
$unitprice = $item->get_total() / $item->get_quantity();
echo "<input type='checkbox' name='productinfo[]' value='" . " " . $item->get_name() . " , " . $item->get_quantity() . " units" . " | " . $item->get_total() ."'>";
and this displays a choice of amount for quantities of 2 and more:
if($item->get_quantity() > 1) {
echo "Amount: " . "<input type='number' name='numberqty' value='" . $item->get_quantity() . "'max='" .$item->get_quantity() . "' min='1' > " . "<br/>";
}
this is how it's displayed on the site itself: (note, from top to bottom they mean "Product name" "Amount" "unit price" "total price of the products")
After selecting the desired checkboxes the user would press a button that would direct them to the next site with the selected products from the earlier page
if 2 is selected by the user here I want the number on the next page be 2, and if 1 is selected then it would be 1. But right now even if 2 is selected, it will display 3 on the next page instead of the desired 2.
is there a way to make this work by updating the given amount into the checkbox value that was set before?
edit: as per request, for clearing up what I want it to do is. To allow me to select a quantity with input type number inside an already defined checkbox made with foreach, which saves the data inside the checkbox manually, the goal is to allow updating the value of the checkbox into one with the new quantity, which is set originally in this piece of code:
$quant = $item->get_quantity();
echo "<input type='checkbox' name='productinfo[]' value='" . " " . $item->get_name() . " , " . $quant . " kpl" . " | " . $item->get_total() ."'>";
here is the full code of pages 2 and 3.
<div class="Etusivu">
<form action="" method="post" style="border:0px solid #ccc">
<fieldset><legend><b>Tuotteiden palautus</b></legend>
<div class="step">
<legend>Askel 2/3</legend>
</div>
<br />
<p class="important">Tilauksen tiedot</p>
<br />
<div class="valitse">
<p class="important">Valitse kaikki tuotteet, jotka haluat palauttaa</p>
</div>
<hr>
<script>
//function for making a checkbox to check all checkboxes
function toggle(source) {
checkboxes = document.getElementsByName('productinfo[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function checkboxupdate {
document.getElementById("numberqty").value = "<?php " " . $item->get_name() . " , " . "2" . " kpl" . " | " . $item->get_total() ?>"
}
</script>
<input type='checkbox' onClick='toggle(this)' />
<p class="selectall">Valitse kaikki tuotteet</p>
<label>Tilauksessa tulleet tuotteet:</p>
<br />
<?php
//Gets and displays data based on certain variables from the database, connects quantity and product name into one string in array
$order = wc_get_order( $ordernumber );
foreach ($order->get_items() as $item ){
$max = $item->get_quantity();
$quant = $item->get_quantity();
$unitprice = $item->get_total() / $item->get_quantity();
echo "<input type='checkbox' name='productinfo[]' value='" . " " . $item->get_name() . " , " . $quant . " kpl" . " | " . $item->get_total() ."'>";
echo '<p>';
echo __('Tuotteen nimi: ' ) . $item->get_name() . '<br>';
if($item->get_quantity() > 1) {
echo "Määrä: " . "<input type='number' name='numberqty' value='" . $quant . "'max='" . $quant . "' min='1' > " . "<br/>";
}
else {
echo __('Määrä: ' ) . $quant . '<br>';
}
if ($item->get_quantity() > 1) {
echo __('Tuotteen kappalehinta: ') . $unitprice . '€' . '<br/>';
}
echo __('Tuotteiden kokonaishinta: ' ) . wc_price($item->get_total()) . '</p>' . '<br/>';
}
echo '<p>'. __('Tilauksen yhteishinta: ') . $order->get_total() . '</p>';
echo "<button onclick='checkboxupdate()'>kokeile</button>";
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id='check' value="Seuraava"/>
<script>
//Checks if any checkboxes have been checked, if not, displays an error
function checkBoxCheck() {
if($('input[name="productinfo[]"]:checked').length) {
console.log("at least one checked");
return true;
}
else {
alert("Valitse vähintään yksi tuote.");
return false;
}
}
//runs the script for checking the checkboxes
$('#check').on('click', checkBoxCheck);
</script>
</label>
<div class="clearfix">
<input type="hidden" name="page" value="2">
</div>
</fieldset>
</form>
<br />
</div>
</body>
</html>
<?php
//checks if the 2nd page submit button has been pressed successfully, if so continues to the next page
} if ($page == 2) {
global $wbdb;
//prints errors, for debugging
if($wpdb->last_error !== ''){
$wpdb->print_error();
//creates a new variable for later input of a comment within a textarea
$comments = $_SESSION['commentone'] = $_POST['comments'];
}
?>
<body>
<div class="Etusivu">
<form action="" method="post" style="border:0px solid #ccc">
<fieldset><legend><b>Tuotteiden palautus</b></legend>
<div class="step">
<legend>Askel 3/3</legend>
</div>
<br />
<p class="important">Palautuksen varmistus</p>
<br />
<div class="valitse">
<p class="important">Haluatko varmasti palauttaa seuraavat tuotteet?</p>
</div>
<hr>
<?php
//Makes an array from given data from the previous page
$test = $_POST['productinfo'];
//variable for counting total price of the chosen items
$total2 = 0;
//variable for counting the total quantity of the selected items
$totalquantity = 0;
//Loop for displaying every selected product individually and their prices and quantities and adding each price and quantity to eachother to allow calculation of total price and quantity
for($i=0; $i < sizeof($test); $i++) {
list($name, $total) = explode("|", $test[$i]);
echo "Nimi: ".$name;
echo "<br>";
echo "Hinta: ".$total . "€";
echo "<br>";
echo "<br/>";
$total2 += $total;
$totalquantity += $quantity;
$names[] = $name;
}
//Sets the total price, quantity into a session
$_SESSION['totalprice'] = $total2;
$_SESSION['totalquantity'] = $totalquantity;
//Uses Json encoding to set the array including the displayed names into session data to allow the displayment of each within the secondary form to insert the data into the database
$_SESSION['product'] = json_encode($names, JSON_UNESCAPED_UNICODE );
?>
<br />
<br />
<h4>Kirjoita alas, miksi haluat palauttaa tuotteen/tuotteet?</h4>
<?php
//variable for textarea comment to allow insertion into database
$comments = $_POST['comments'];
//Inside textarea $comments displays the data inside it to save it and insert it into database that way?>
<textarea id='commenter' name='comments' cols='30' rows='4' placeholder='Kirjoita tähän:'><?php echo $comments; ?></textarea>
<div class="refundprice">
<?php //inside label is a $total2 variable which is the total price of everything that was checked and taken to this page ?>
<?php echo '<label>Palautettavien tuotteiden yhteishinta: ' . $total2 . '€' . '</label>'
?>
</div>
<div class="clearfix">
<input type="hidden" name="page" value="3">
<input type="submit" class="signupbtn" name="sendrqst" value="Lähetä">
</div>
</fieldset>
</form>
</div>
</body>
</html>
<?php
}
?>
Upvotes: 1
Views: 5105
Reputation: 15620
First off, let's "optimize" your toggle()
function:
function toggle(source) {
// 1. Define `checkboxes` and `i` as local variables using the `var`
// keyword.
var checkboxes = document.getElementsByName('productinfo[]'), i;
// 2. I also "simplified" your `for` expression - no extra "n" here.
for (i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
or why not use jQuery:
function toggle(source) {
jQuery( ':checkbox[name="productinfo[]"]' )
.prop( 'checked', source.checked );
}
Now, pick and try one of these options, or both:
I could see that you tried to use the checkboxupdate()
function to dynamically update the checkbox
value — or more precisely, the quantity that the user inputted in the quantity field. But it doesn't work because there are no elements with the id
of numberqty
and secondly, the PHP variable of $item
there is undefined and will cause a fatal error. (And even if you got these fixed, you'll still need to adjust the code to make it actually works.)
Note that this and the other solution are based on your format for the checkbox
value — note the space at the beginning: {item name} , {quantity} kpl | {total price}
.
On step #2, in the foreach
loop, apply these changes:
foreach ($order->get_items() as $item ){
// 1. Wrap the item inside this `div`.
echo '<div class="order-item">';
... your code here ...
// 2. For the quantity field, replace the name='numberqty' with
// class='numberqty'. I.e. use `class` instead of `name`.
if($item->get_quantity() > 1) {
echo "Määrä: " . "<input type='number' class='numberqty' value='" . $quant . "'max='" . $quant . "' min='1' > " . "<br/>";
}
... your code here ...
// 3. Make sure to close the `div`.
echo '</div>';
}
Then use this checkboxupdate()
which utilizes jQuery:
function checkboxupdate() {
jQuery( ':checkbox[name="productinfo[]"]' ).each( function() {
var $order_item = jQuery( this ).closest( '.order-item' ),
$qty = $order_item.find( 'input.numberqty' );
if ( $qty.length ) {
jQuery( this ).val( this.value.replace(
/\d+ (kpl \| [0-9\.]+)$/,
( $qty.val() || 1 ) + ' $1'
) );
}
});
}
And if necessary (because your on step #3, in the $name
below already contains the quantity),for
loop, you can get the quantity (without the unit or the text kpl
) like so:
for($i=0; $i < sizeof($test); $i++) {
list($name, $total) = explode("|", $test[$i]);
// 1. Retrieve the preferred refund quantity.
list( $name2, $quantity ) = explode( ' , ', $name );
$quantity = intval( $quantity ); // strips the " kpl"
echo 'The quantity: ' . $quantity . '<br>'; // test
... your code here ...
}
And for the button which calls the checkboxupdate()
function, make sure that the button type
is set properly — if you don't, it defaults to a submit button, and clicking on it will submit the form instead of just updating the checkbox
value:
<button onclick='checkboxupdate()' type="button">kokeile</button>
or append return false;
to the onclick
attribute to prevent the default action:
<button onclick='checkboxupdate(); return false'>kokeile</button>
Note that this is just one of the different ways you can bring the quantity selected on to the next page (or from step #2 to step #3). And with this option, you would just ignore the checkboxupdate()
and the button that calls the function.
Make these changes in the foreach
loop on step #2:
// 1. Add the `$i => `
foreach ($order->get_items() as $i => $item ){
... your code here ...
// 2. Add the `; $i` to the value - at the end.
echo "<input type='checkbox' name='productinfo[]' value='" . " " . // wrapped
$item->get_name() . " , " . $quant . " kpl" . " | " . $item->get_total() ."; $i'>";
... your code here ...
// 3. Change the `name` to numberqty[ $i ].
if($item->get_quantity() > 1) {
echo "Määrä: " . "<input type='number' name='numberqty[" . $i . "]' value='" // wrapped
. $quant . "'max='" . $quant . "' min='1' > " . "<br/>";
}
... your code here ...
}
Or just remove the " , " . $quant . " kpl" .
from the productinfo
field, where the markup would be:
echo "<input type='checkbox' name='productinfo[]' value='" . " " . // wrapped
$item->get_name() . " | " . $item->get_total() ."; $i'>";
Before the for
loop on step #3, add the $qty_array
variable as you can see below, then make the other changes inside that loop:
// 1. Retrieve all the POSTed numberqty values.
$qty_array = isset( $_POST['numberqty'] ) ? (array) $_POST['numberqty'] : array();
for($i=0; $i < sizeof($test); $i++) {
list($name, $total) = explode("|", $test[$i]);
// 2. Retrieve the preferred refund quantity.
list( $total, $index ) = explode( '; ', $total );
$quantity = isset( $qty_array[ $index ] ) ? intval( $qty_array[ $index ] ) : 1;
echo 'The quantity: ' . $quantity . '<br>'; // test
// 3. Update the quantity in the item *name*.
list( $name ) = explode( ' , ', $name );
$name .= ' , ' . $quantity . ' kpl';
echo 'Nimi: ' . $name . '<br>';
... your code here ...
}
If you removed the " , " . $quant . " kpl" .
from the productinfo
field, ignore the following list()
:
//list( $name ) = explode( ' , ', $name ); // purposely commented out
And that's really all you need, no custom JavaScript necessary.
Upvotes: 1