javascript - unCaught type error: cannot read property 'null' value for document.getElementByID().value; -
i trying value of input field console says cannot read property null value.i have used document.getelementbyid().value function. view source code displays values javascript variable not getting value. following code:
<script type="text/javascript"> function addcart(id,name,price) { var quantity=document.getelementbyid("quantity_"+id).value;//this line gets error $.ajax({ type:'post', url:'addcart.php', data:{ item_id:id, item_name:name, item_quantity:quantity, item_price:price }, success:function(response) { document.getelementbyid("cart").innerhtml=response; } }); } </script>
i tried using jquery val() function, follows...
<script type="text/javascript"> function addcart(id,name,price) { var quantity = $('#quantity_'+id).val(); //this line $.ajax({ type:'post', url:'addcart.php', data:{ item_id:id, item_name:name, item_quantity:quantity, item_price:price }, success:function(response) { document.getelementbyid("cart").innerhtml=response; } }); } </script>
look html code:
<?php while($row = mysqli_fetch_array( $fetch_customer_menu_result)) { $item_id=$row['item_id']; $item_name=$row['item_name']; $item_price=$row['item_price']; echo ' <div class="w3-col l8 w3-col s8"> <input class="form-control w3-left" type="number" placeholder="count" id="quantity_'.$row['item_id'].'" value="1"> <span class="w3-right"><u>rate (each):</u></span><br> <span class="w3-right w3-large"><b>rs. '.$row['item_price'].'</b></span> </div> </div> <div class="w3-col l12 w3-center" style="margin-top: 5px"> <button type="button" class="w3-red btn form-control" onclick="addcart(\' '.$item_id.' \',\' '.$item_name.' \',\' '.$item_price.' \')" >add cart</button> </div> </div> </div>'; } ?>
uncaught type error: cannot read property '
null
' valuedocument.getelementbyid().value;
this error means document.getelementbyid()
returns null
pointer (i.e. can't find element looking for, returns null
), , trying find value of field doesn't exist (document.getelementbyid("quantity_"+id).value
becomes null.value
, , null
not have field named value
).
why?
the reason (in case) value pass in id
in addcart
function incorrect. however, there few causes. follow these debugging steps:
make sure order of parameters same defined in function , calling (i.e. not passing in
name
should passing inid
)add line above line error:
console.log("quantity_"+id)
, use browser console check if text box has exactly id - if doesn't, problem.make sure
addcart
being called when text field on screen - ensure don't delete text field , calladdcart
, ,addcart
doesn't called before element has been created.make sure there not 2 functions name
addcart
.
Comments
Post a Comment