Skip to content Skip to sidebar Skip to footer

How To Do Validation Inside Foreach

I have a form which has some text fields. Text fields may increase or decrease according to database table. If there are 3 warehouses in database it will show 3 text boxes with ava

Solution 1:

Try to use html5 required attribute. This set of code may help you.

<input type="number" 
       min="1" 
       max="<?php echo $data->wh_product_qty; ?>" 
       name="<?php echo $data->wh_warehouse_id;?>" 
       required="required" 
       placeholder="<?php echo $data->wh_product_qty; ?> Available" />

Solution 2:

You cannot use an id multiple times in the document, it needs to be unique. Either use classes to identify/group elements, or enumerate the ids:

<?php
    $i = 0;
    if (!empty($ware_details)) {
         foreach ($ware_details as $data) {
              ?>  
                    <div class="form-group">
                        <label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
                        <input type="number" id="return_pro<?php echo $i; ?>" class="form-control" base_url="<?php echo site_url(); ?>"  name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
                        <div class="dataDrop"></div>
<input type="hidden" id="quantity<?php echo $i; ?>" value="<?php echo $data->wh_product_qty; ?>"/>
                    </div>
            <?php 
            $i++;
        } }?>
<script>
function check(i) {
    var stock = document.getElementById('quantity'+i).value;
        var return_stock = document.getElementById('return_pro'+i).value;
        if (parseFloat(stock) < parseFloat(return_stock))
        {
            alert("Return product can't be more than total stock");
            document.getElementById('return_pro'+i).focus();
            return false;
        }
        //alert(return_stock);
        return false;
}
// then in the validation trigger:
     for (var i=0; i< <?php echo $i; ?>; i++)
         check(i);

Post a Comment for "How To Do Validation Inside Foreach"