Home > OS >  How can I increment and decrement value with unique id?
How can I increment and decrement value with unique id?

Time:05-05

I have this loop, The id is unique. When I try to increment it is working for only one input field. How can I increment and decrement using unique id?

          @forelse($allproduct as $key=>$data)
                            <tr>
                                <td data-label="@lang('Date')">
                                     <div  style="display:flex; ">
                                          <input type="text" value=""  id="qtyid[{{$data->product_id}}]" min="0">
                                       <div >
                                          <div  onclick="incrementValue()"> </div>
                                          <div  onclick="decrementValue()">-</div>
                                       </div>

                                    </div>
                                 </td>
                            </tr>
          @endforelse

Javascript

function incrementValue()
    {
        var value = parseInt(document.getElementById("qtyid").value, 10);
        value = isNaN(value) ? 0 : value;
        value  ;
        document.getElementById('qtyid').value = value;
    }


    function decrementValue()
    {
        var value = parseInt(document.getElementById('qtyid').value, 10);
        value = isNaN(value) ? 0 : value;

        value--;
        if(value == -1) {
            value = 0;
        }
        document.getElementById('qtyid').value = value;
    }

CodePudding user response:

I suggest you use an approach that doesn't need IDs.

function incrementValue(e)
    {
        // use the quantity field's DOM position relative to the button that was clicked
        const qty = e.target.parentNode.parentNode.querySelector("input.req.amnt");
        var value = parseInt(qty.value, 10);
        value = isNaN(value) ? 0 : value;
        value  ;
        qty.value = value;
    }


    function decrementValue(e)
    {
        const qty = e.target.parentNode.parentNode.querySelector("input.req.amnt");
        var value = parseInt(qty.value, 10);
        value = isNaN(value) ? 0 : value;

        value--;
        if(value == -1) {
            value = 0;
        }
        qty.value = value;
    }
@forelse($allproduct as $key=>$data)
                            <tr>
                                <td data-label="@lang('Date')">
                                     <div  style="display:flex; ">
                                          <input type="text" value=""  min="0">
                                       <div >
                                          <div  onclick="incrementValue(event)"> </div>
                                          <div  onclick="decrementValue(event)">-</div>
                                       </div>

                                    </div>
                                 </td>
                            </tr>
          @endforelse

  • Related