如何使用用户输入更新复选框值

时间:2018-10-30 08:20:16

标签: php wordpress woocommerce

我正在尝试使用一段代码来显示表中的数据,并将数据保存在一个复选框中,如果选中该复选框,则将其发布。但是我在尝试选择与原始数量不同的数量上遇到了问题,由于页面加载时复选框设置为石头,它将始终选择最大数量,我可以通过某种方式更新复选框的值吗? ?复选框代码如下:

$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/>";
              }

这是它在网站本身上的显示方式:(请注意,它们从上到下表示“产品名称”,“金额”,“单价”,“产品总价”)enter image description here

选中所需的复选框后,用户将按下一个按钮,该按钮会将其与上一页中选择的产品一起引导到下一个站点

如果用户在此处选择了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

  }

?>

1 个答案:

答案 0 :(得分:1)

首先,让我们“优化”您的toggle()函数:

  • 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;
      }
    }
    

    或者为什么不使用jQuery:

    function toggle(source) {
      jQuery( ':checkbox[name="productinfo[]"]' )
        .prop( 'checked', source.checked );
    }
    

现在,选择并尝试以下选项之一,或同时选择两者:

解决方案1:JavaScript + PHP

我可以看到您尝试使用checkboxupdate()函数来动态更新checkbox值,或更准确地说,是用户在数量字段中输入的数量。但这是行不通的,因为id的{​​{1}}没有元素,其次,numberqty的PHP变量未定义,将导致致命错误。 (即使您已解决这些问题,您仍然需要调整代码以使其真正起作用。)

请注意,此解决方案和其他解决方案均基于您的$item值格式-请注意开头的空格:checkbox

  1. 在第二步的{item name} , {quantity} kpl | {total price}循环中,应用以下更改:

    foreach
  2. 然后使用利用jQuery的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>'; }

    checkboxupdate()
  3. ,如果需要,(因为下面的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' ) ); } }); } 已包含数量),在步骤{3}的$name循环中,您可以获取数量(不含单位或文本for),如下所示:

    kpl

对于调用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 ... } 函数的按钮,请确保正确设置了按钮checkboxupdate()-如果不正确,则默认为一个提交按钮,单击该按钮将提交表单,而不仅仅是更新type值:

checkbox

或将<button onclick='checkboxupdate()' type="button">kokeile</button> 附加到return false;属性中以防止执行默认操作:

onclick

解决方案2:仅PHP

请注意,这只是将所选数量带到下一页(或从步骤#2到步骤#3)的一种不同方式。使用此选项,您只需忽略<button onclick='checkboxupdate(); return false'>kokeile</button> 调用该函数的按钮。

  1. 在第二步的checkboxupdate()循环中进行以下更改:

    foreach

    或者只是从// 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 ... } 字段中删除" , " . $quant . " kpl" .,标记将为:

    productinfo
  2. 之前,在步骤3的echo "<input type='checkbox' name='productinfo[]' value='" . " " . // wrapped $item->get_name() . " | " . $item->get_total() ."; $i'>"; 循环中,添加for变量,如下所示,然后进行其他更改 inside < / em>该循环:

    $qty_array

    如果您从// 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 ... } 字段中删除了" , " . $quant . " kpl" .,请忽略以下productinfo

    list()

这实际上就是您所需要的,不需要自定义JavaScript。