Я пытаюсь получить фрагмент кода, который отображает данные из таблицы, сохраняет данные внутри флажка, который, если выбран, отправляет его вперед. Но я застрял в проблеме с попыткой выбрать количество, отличное от исходного, оно всегда выберет максимальное количество из-за того, что флажок установлен на камень при загрузке страницы, могу ли я каким-то образом обновить значения флажка ? Код флажка выглядит так:
$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() ."'>";
, и это отображает выбор суммы для количеств 2 и более:
if($item->get_quantity() > 1) {
echo "Amount: " . "<input type='number' name='numberqty' value='" . $item->get_quantity() . "'max='" .$item->get_quantity() . "' min='1' > " . "<br/>";
}
это то, как это отображается на самом сайте: (обратите внимание, сверху вниз они означают «Название продукта», «Количество», «Цена за единицу», «Общая цена продуктов»)
После выбора нужных флажков пользователь нажимает кнопку, которая направляет их на следующий сайт с выбранными продуктами с более ранней страницы
если пользователь выбрал здесь 2, я хочу, чтобы число на следующей странице было 2, а если выбрано 1, то будет 1. Но сейчас, даже если выбрано 2, на следующей странице будет отображаться 3 вместо желаемого 2.
Есть ли способ заставить эту работу, обновив заданную сумму в значение флажка, который был установлен ранее?
edit: согласно запросу, для выяснения того, что я хочу сделать, это. Чтобы позволить мне выбрать количество с номером типа ввода внутри уже определенного флажка, созданного с помощью foreach, который сохраняет данные внутри флажка вручную, цель состоит в том, чтобы позволить обновить значение флажка до единицы с новым количеством, которое установлено первоначально в этом куске кода:
$quant = $item->get_quantity();
echo "<input type='checkbox' name='productinfo[]' value='" . " " . $item->get_name() . " , " . $quant . " kpl" . " | " . $item->get_total() ."'>";
вот полный код страниц 2 и 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
}
?>