【问题标题】:How to update checkbox values using user input如何使用用户输入更新复选框值
【发布时间】:2018-10-30 08:20:15
【问题描述】:

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

$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.

有没有办法通过将给定数量更新为之前设置的复选框值来完成这项工作?

编辑:根据要求,清除我想要它做的是。为了允许我在使用 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

  }

?>

【问题讨论】:

  • 你能简单描述一下你想要什么吗??
  • 你能把完整的代码贴在这里吗?我不明白你的要求。
  • 简而言之,我希望能够更改已创建的复选框@bhanusengar 中的值
  • 将第 2 页和第 3 页的完整代码(重要的)添加到原始帖子@OutsourceWordPress
  • 是的,它会为您提供为订单中相应产品/项目选择的适当数量。因此,如果您将数量字段的名称更改为numberqty[],在下一页(即第 3 页)上,在list($name, $total) = explode("|", $test[$i]); 之后,您可以添加例如$quantity = $_POST['numberqty'][$i];。试一试,看看效果如何..

标签: php wordpress woocommerce


【解决方案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 );
    }
    

现在,选择并尝试以下选项之一,或两者兼而有之:

方案一:JavaScript + PHP

我可以看到您尝试使用checkboxupdate() 函数来动态更新checkbox 值——或者更准确地说,是用户在数量字段中输入的数量。但它不起作用,因为numberqtyid没有元素,其次,$item的PHP变量未定义,会导致致命错误。 (即使您已经修复了这些问题,您仍然需要调整代码以使其真正起作用。)

请注意,此解决方案和其他解决方案基于您的 checkbox 值格式 — 请注意开头的空格:{item name} , {quantity} kpl | {total price}

  1. 在第 2 步,在 foreach 循环中,应用这些更改:

    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>';
    }
    
  2. 然后使用这个使用 jQuery 的checkboxupdate()

    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已经包含了数量),在第3步,在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 属性以防止默认操作:

<button onclick='checkboxupdate(); return false'>kokeile</button>

解决方案 2:仅限 PHP

请注意,这只是您可以将所选数量带到下一页(或从第 2 步到第 3 步)的不同方法之一。使用此选项,您将忽略checkboxupdate() 调用该函数的按钮。

  1. 在第 2 步的 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 ...
    
    }
    

    或者只是从 productinfo 字段中删除 " , " . $quant . " kpl" .,标记将是:

    echo "<input type='checkbox' name='productinfo[]' value='" . " " . // wrapped
      $item->get_name() . " | " . $item->get_total() ."; $i'>";
    
  2. 步骤#3 的for 循环之前,添加$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 ...
    }
    

    如果您从productinfo 字段中删除了" , " . $quant . " kpl" .,请忽略以下list()

    //list( $name ) = explode( ' , ', $name ); // purposely commented out
    

这就是你真正需要的,不需要自定义 JavaScript。

【讨论】:

  • 这就像一个魅力,只有一个 php 设法解决了被诅咒的数量选择中的所有问题,非常感谢!
  • 不客气,很高兴它对您有所帮助。 =) 对不起,如果我把checkboxupdate() / "kokeile" 弄错了。我只是想我也应该给你 JS + PHP 选项,但这当然不是优先事项,尽管这是我建议的第一个解决方案。 :)
  • 我也不是 100% 确定 checkboxupdate() 是不是错了,我可能做错了,但你能实际翻译也很好(或者我想因为有没有我在原始代码中看到的“kokeile”)来匹配语言,这也是最重要的部分,其中一个修复至少有效。
  • 如果(且仅当)你想要,我可以从答案中删除 JS + PHP 解决方案吗?实际上,还有另一种可能的解决方案 - 并且在用户无法弄乱复选框值中的总价格方面可能会更好 - 我们将订单号带到下一步(#3)并使用与步骤#2 相同的foreach(我的意思是$order-&gt;get_items())。你想看吗?
  • 当然,如果你想添加它,并且不需要删除JS + PHP方法,它可能会在将来为其他人工作。
猜你喜欢
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2014-06-05
  • 2022-01-17
  • 1970-01-01
相关资源
最近更新 更多