Error onclick Uncaught ReferenceError

1

I want to call a method of my JS and pass a variable but it gives me Uncaught ReferenceError, how can I fix this.

PHP / HTML

<div class="col-4 col-md-2 topbutton ">                                        
                            <input  name="cart_id" value=" <?php echo$q["product_id"]; ?>"> 
                            <input type="button" class="btn btn-danger eliminar_cart" value="Elimina" id="<?php echo$q["product_id"]; ?>" onclick="eliminar_cart(this)">                                           
                        </div>

js

function eliminar_cart(id) {
    var cart_id = id.id;
    alert(cart_id);}
    
asked by Aaron M Fonseca 26.09.2018 в 02:55
source

2 answers

2

Depending on the value that is returned in $q , it is only necessary to place your js code at the beginning of your html file (at the beginning of body or in head ), this between tags <script> or including the js file.

function eliminar_cart(id) {
    var cart_id = id.id;
    alert("msg:" + cart_id);}
<div class="col-4 col-md-2 topbutton ">          <input  name="cart_id" value="valorRetornadoen$q"> 
 <input type="button" class="btn btn-danger eliminar_cart" value="Elimina" id="idRetornadoen$q" onclick="eliminar_cart(this);">                                           
                        </div>
    
answered by 26.09.2018 / 03:23
source
2

There are two recommended practices you are forgetting:

  • The JS code must always be inside a DOMContentLoaded block, so never try to use DOM elements before the DOM is fully loaded.
  • It is convenient that our HTML code is as independent as possible. Therefore, avoid putting functions inside the HTML elements. In the example I removed the function that was inside the button, changing it by a listener in JS. This will also give us the advantage of this directly.
  • I leave the code, as a possibility to solve the problem by applying good practices.

    <script>
      document.addEventListener("DOMContentLoaded", function(event) {
        var btn1 = document.getElementById("btn1");
        btn1.addEventListener("click", function(e) {
            alert(this.id);
        }, false);
      });
    </script>
    
    <div class="col-4 col-md-2 topbutton ">
      <input name="cart_id" value="Test...">
      <input type="button" class="btn btn-danger eliminar_cart" value="Elimina" id="btn1">
    </div>
        
    answered by 26.09.2018 в 03:36