onclick with . append sending function with variable

Asked

Viewed 50 times

1

First of all, my code:

function renderLiberarCarro(liberar, userId, docId){
  var documentId =  docId;
  var aviso = '<span class="badge badge-pill badge-sussess">Liberar</span>';
  var photo = '<%= dataUser.photo %>';
  if(photo == null){
      photo =  "public/assets/images/users/avatar-2.jpg";
  }
$("table.liberar tbody").append(
    '<tr class='+documentId+'>'+

        '<td class='+liberar.marca+'> Cliente Medcar: '+ liberar.cliente +'</td>'+
        '<td class='+liberar.marca+'>'+ liberar.marca +'</td>'+
        '<td class='+liberar.marca+'>'+ liberar.modelo +'</td>'+
        '<td class='+liberar.marca+'>'+ liberar.ano +'</td>'+
        '<td class='+liberar.marca+'>'+ aviso +'</td>'+
        '<td class='+liberar.marca+'><a onclick=\"liberarCarro('+documentId+')\" id="'+ docId +'" href="#" data="'+docId+'" class="btn btn-secondary action-liberar btn-sm waves-effect">Liberar</a> '+
    '</tr>'
    );

};
function liberarCarro(docId){
    console.log(docId)
}

at last td insert an onclick into it and call the car release function and step a value, but instead of seeing the value the return is being this:

<a onclick="liberarCarro(eVzsQHCk4UozJ4MQI26S)" id="eVzsQHCk4UozJ4MQI26S" href="#" data="eVzsQHCk4UozJ4MQI26S" class="btn btn-secondary action-liberar btn-sm waves-effect">Liberar</a>

is returning the full tag, what I expected back was just: eVzsQHCk4UozJ4MQI26S. Can anyone tell me why?

Thank you

  • SOLVED: '<td class='+release.brand+'><a onclick="release Box("'+documentId+'")" id="'+ docId +'" href="#" data="'+docId+'" class="btn btn-Secondary action-release btn-Sm Waves-Effect">Release</a> '+

1 answer

1


It turns out that you are passing to the function a text string without quotation marks:

onclick="liberarCarro(eVzsQHCk4UozJ4MQI26S)"
                                ↑
                     sem aspas delimitadoras

In this way, what is sent to the function as parameter is the element itself that called the onclick.

If the parameter was a numerical value, then the function would receive that value. For example:

onclick="liberarCarro(103)"
                       ↑
                     número

The console.log(docId) display 103.

In this case, if you do not want to send the element itself to the function, you must always delimit the argument with single or double quotes (in your case, single quotes would be escaped because the onclick uses double quotes and concatenation is done with single quotes).

It would look like this (no need to escape the double quotes from the onclick as you’ve been doing):

onclick="liberarCarro(\''+documentId+'\')"
                       ↑               ↑
                    aspas simples escapadas

Browser other questions tagged

You are not signed in. Login or sign up in order to post.