简体   繁体   中英

DOM selector giving null in Vanilla JavaScript but working in jquery

I am selecting an id using vanilla JS but ("qty").value; is giving me null answer but using the same code through jQuery is working fine after else my jQuery code line

function manage_cart(pid, type) {
  if (type == 'update') {
    var qty = document.getElementById(pid + "qty").value;
  } else {
    var qty = jQuery("#qty").val();
  }

  var ajax = new XMLHttpRequest();
  ajax.open("post", "manage_cart.php", true);
  ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // Response
      var response = this.responseText;
      if (type == 'update' || type == 'remove') {
        window.location.href = 'cart.php';
      }
      document.querySelector('.cart-a span').innerHTML = response;
    }
  };
  
  var data = new URLSearchParams({
    pid,
    qty,
    type
  });
  ajax.send(data);
}

This is my vanilla JS code

function manage_cart(pid, type) {
  if (type == 'update') {
    var qty = document.getElementById(pid + "qty").value;
  } else {
    var qty = document.getElementById('qty').value;
  }
  
  var ajax = new XMLHttpRequest();
  ajax.open("post", "manage_cart.php", true);
  ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // Response
      var response = this.responseText;
      if (type == 'update' || type == 'remove') {
        window.location.href = 'cart.php';
      }
      document.querySelector('.cart-a span').innerHTML = response;
    }
  };
  
  var data = new URLSearchParams({
    pid,
    qty,
    type
  });
  ajax.send(data);
}

My html and php code looks like this in which the id is different for each product but remove does need pid in the selector.

 <div class="basket-product-c">
      <?php
                                        if(isset($_SESSION['cart'])){
                                            foreach($_SESSION['cart'] as $key=>$val){
                                            $productArr=get_product($con,'','',$key);
                $price=$productArr[0]['price'];
                $qty=$val['qty'];
    ?>
        <div class="price-c"><?php echo $price?></div>
        <div class="quantity-c">
          <input type="number" class="quantity-field-c" id="<?php echo $key?>qty" value="<?php echo $qty?>"/>
          <br/><a href="javascript:void(0)" onclick="manage_cart('<?php echo $key?>','update')">update</a>
        </div>
        <div class="subtotal-c"><?php echo $qty*$price?></div>
        <div class="remove-c">
        <a href="javascript:void(0)" onclick="manage_cart('<?php echo $key?>','remove')">Remove</a>
        </div>
      
        <?php } } ?>

If you log var qty to the console, are you getting null, or is it picking up the element? The only reason I can think of as to why the vanilla js version is not working, is that the jquery id selector fires slower than a getElementById(). Ideally, there would be no difference, since jquery('#element') uses document.getElementById() under the hood.

Maybe do as @Elikill58 suggested and delay the selection by wrapping that line in a setTimeout() function.

Also, getElementById().value will return undefined if there's no value attribute, or blank if there is a value attribute present for that tag, but there is no value set.

If the element is not being picked up at all by the selector, you'll get null as a response.

Try this and see if it works:

function manage_cart(pid, type) {
  if (type == 'update') {
    var qty = document.getElementById(pid + "qty").value;
  } else {
    setTimeout(() => {
      var qty = document.getElementById('qty').value;
    }, 200)
  }

You can play around with the delay timing to find one which is ideal for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM