Skip to content
Advertisement

change input value of element with jquery based on localstorage

I use php to create some html product elements for a shopping cart based on a database .

enter image description here

The problem was that if I changed the product quantity and refreshed my page the quantity is changed back to ‘1’ . So I used localStorage to store the quantities of each product . If I refresh , the quantities remain unchanged succesfully but If I click on ‘+’ image element to add to quantity the input value on the product quantity change is displayed only if I refresh my page. So the problem is how to update my code to dynamically add to product quantity and save the quantity to localstorage the same time .

My code :

cart.php

<div class="cart__table table-responsive">
                      <table width="100%" class="table" id  ="cartItems">
                          <thead>
                            <tr>
                              <th>PRODUCT</th>
                              <th>NAME</th>
                              <th>UNIT PRICE</th>
                              <th>QUANTITY</th>
                              <th>TOTAL</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php 
                              if(isset($_COOKIE)){
                                $count = 0;
                                foreach($_COOKIE as $i){
                                  $count++;
                                  if($count ==1 ){
                                    continue;
                                  }
                                  $product = json_decode($i,true);
                                  echo "
                                  <tr 
                                    class ='product-columns'>
                                      <td class ='product__thumbnail'>
                                        <img src = ".$product["image"]." />
                                      </td>
                                      <td class='product__name'>
                                        <h3> ".$product["called"]." </h3>
                                        <small class = 'cartItemID' style = 'display:none;'> ".$product["code"]." </small>
                                        <small>".$product["soldAt"]."</small>
                                      </td>
                                      <td class='product__price'>
                                        <div class='price'>
                                          <span class='new__price'>".$product["costs"]."</span>
                                        </div>
                                      </td>
                                      <td class='product__quantity'>
                                        <div class='input-counter'>
                                            <div>
                                                <span class='minus-btn'>
                                                    <svg>
                                                        <use xlink:href='../images/sprite.svg#icon-minus'></use>
                                                    </svg>
                                                </span>
                                            <!--this is the element i want to change  -->
                                                <input 
                                                  type='text'  min='1' 
                                                   max='10' 
                                                  class='counter-btn' disabled
                                                  name = ".$product["code"]."
                                                   
                                                />
                                                <span class='plus-btn' >
                                                    <svg>
                                                        <use xlink:href='../images/sprite.svg#icon-plus'></use>
                                                    </svg>
                                                </span>
                                            </div>
                                        </div>
                                      </td>
                                      <td class='product__subtotal'>
                                          <div class='price'>
                                              <span class='new__price'>$250.99</span>
                                          </div>
                                          <a class='remove__cart-item'>
                                              <svg>
                                                <use xlink:href='../images/sprite.svg#icon-trash'></use>
                                              </svg>
                                          </a>
                                      </td>
                                  </tr>
                                  ";
                                  
                                }
                               <!-- when the php loads set input values to localstorage values -->  
                                echo "
                                  <script type = 'text/javascript'>
                                    var quantities = document.querySelectorAll('.counter-btn'); 
                                     quantities.forEach(q=>q.value = getSavedValue(q.name));
                                  </script>
                                ";

                              }else{
                                echo "<h1> No products have been added.  </h1>";
                              }


                            ?>
                                
                          </tbody>
                        </table>
                      </div>

So with the above code I create html elements using php and set their quanity input to localstorage value of corresponding element

In a jquery script I have function to add to quantity when you click ‘+’ and update localstorage

jquery.js

    //Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
  var name = e.name;  // get the sender's id to save it . 
  var val = e.value; // get the value. 
  localStorage.setItem(name, val);// Every time user writing something, the localStorage's value will override . 
}

//get the saved value function - return the value of "v" from localStorage. 
function getSavedValue  (v){
  if (!localStorage.getItem(v)) {
      return "1";// You can change this to your defualt value. 
  }
  return localStorage.getItem(v);
}

function changeValue(name,val){
  localStorage.setItem(name , val);
}


//document ready 
$(".plus-btn").click((e)=>{
    var itmQuantity = parseInt($(e.target).closest('tr').find('.counter-btn').val());
    console.log(itmQuantity); //number
    if(itmQuantity!=10){
      $(e.target).closest('tr').find('.counter-btn').attr('value' , itmQuantity+1);
      var cd =  $(e.target).closest('tr').find('.counter-btn').attr('name');
      changeValue(cd,itmQuantity+1);
    }
  }); 

Advertisement

Answer

Try placing this code inside one of your functions maybe inside ‘changeValue()’

$('.counter-btn').attr('value', 999);

if you do place it inside changeValue() the actual code will be

$('.counter-btn').attr('value', val);

Its best to give the input for .counter-btn an actual ‘id’ attribute then you can be more specific and use

<input id="counter-btn-1" type='text'min='1' max='10' class='counter-btn' disabled name=".$product["code"]."/>                                                                                               
$('#counter-btn-1').attr('value', val);
Advertisement