Pass multiple values with onClick in HTML link
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
Solution: Pass multiple arguments with onclick for html generated in JS
For html generated in JS , do as below (we are using single quote as string wrapper). Each argument has to wrapped in a single quote else all of yours argument will be considered as a single argument like functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument with single quote, give a separator comma in between and then start next argument with a single quote. (This is the magic code to use
'\',\''
)
Example:
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId +'\',\'' + user + '\')">Re-Assign</a> </td> </tr>');
If valuationId
and user
are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
<a href=# onclick="return ReAssign(valuationId,user)">Re-Assign</a>
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo '<a href=# onclick="return ReAssign(\'' + $valuationId + '\',\'' + $user + '\')">Re-Assign</a>';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId + '\',\'' + user + '\')">Re-Assign</a> </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}