Home > Blockchain >  Javascript onclick problem with multiple parameters
Javascript onclick problem with multiple parameters

Time:03-02

I am trying to pass multiple parameters in a 'onclick' but it is not working and JS gave me headaches.

When clicking the 'div' and going to agregarADetalleMenu gives me this error:

SyntaxError: missing ) after argument list

function LlenarTableMenu(data) {
  $('#cards-productos').empty();

  $.each(data, function(i, val) {

    var block2 = '<div  onclick="agregarADetalleMenu('   val.id   ', '   val.name   ', '   val.price   ')">'  
      '<figure > '  
      '<div >'  
      ' <img src="'   val.imagen   '">'  
      @* '<center><a  href="#"><i ></i> AGREGAR </a></center>'   *@ '</div>'  
      '<figcaption >'  
      '<a href="#" >'   val.name   '</a>'  
      '<div > '  
      '<div >'  
      @* '<span >'   val.price.toFixed(2)   '</span>'   *@ '<span style="display: none;" >'   val.id   '</span>'  
      '</div>'  
      '</div>'  
      '</figcaption> '  
      '</figure> '  
      '</div>';

    $("#cards-productos").append(block2);
  });
}

CodePudding user response:

Do you mean this?

Note I wrapped the function values in quotes - you nested your quotes

function LlenarTableMenu(data) {
  $('#cards-productos').html(

  data.map(val => `<div  onclick="agregarADetalleMenu('${val.id}','${val.name}',${val.price})">
      <figure >
        <div >
          <img src="${val.imagen}">
          <center><a  href="#"><i ></i> AGREGAR </a></center>
        </div>
        <figcaption >
          <a href="#" >${val.name}</a>
          <div >
            <div >
              <span >${val.price.toFixed(2)}</span>
              <span style="display: none;" >${val.id}</span>
            </div>
          </div>
        </figcaption>
      </figure>
    </div>`).join("")
  );
}

This is better

function LlenarTableMenu(data) {
  $('#cards-productos').html(

  data.map(val => `<div   data-id="${val.id}" data-name="${val.name}" data-price="${val.price}">
      <figure >
        <div >
          <img src="${val.imagen}">
          <center><a  href="#"><i ></i> AGREGAR </a></center>
        </div>
        <figcaption >
          <a href="#" >${val.name}</a>
          <div >
            <div >
              <span >${val.price.toFixed(2)}</span>
              <span style="display: none;" >${val.id}</span>
            </div>
          </div>
        </figcaption>
      </figure>
    </div>`).join("")
  );
}

and then have

$('#cards-productos').on("click",".agregar",function() {
  agregarADetalleMenu(this.dataset.id,this.dataset.val,this.dataset.price)
})

CodePudding user response:

You're missing quotes around the values being passed in to the function. Because you already used single and double quotes in your string, you can use escaped single (or double) quotes as follows:

onclick="agregarADetalleMenu(\''   val.id   '\', \''   val.name   '\', \''   val.price   '\')"
  • Related