Mr Fish
Mr Fish

Reputation: 45

onclick passing numbers and strings

When I put a string value into an onclick the console returns 'Uncaught SyntaxError: Unexpected token ILLEGAL'? It works fine if its just a number but not if its a string!

Code:

document.getElementById("productMenu").innerHTML += "<div class=\"leftMenuItems\"    onclick=\"javascript:showResources(" + p_codes + ");\">" + p_codes + " - " + p_names + "</div>";

<div class="leftMenuItems" onclick="javascript:showResources(1234ABC);">Product Name</div>

Upvotes: 2

Views: 8308

Answers (4)

user2387092
user2387092

Reputation: 11

Try this, it worked for me.

Pass string inside of quote in the following string.format: HttpUtility.HtmlEncode("'"+personnelPhotoList[j].name.Trim()+"'")

Code sample:

StringBuilder strPhotos = new StringBuilder();

strPhotos.Append(String.Format("<div class=\"div_employee_img\">
         <a href=\"#\" onclick=\"DeletePhoto({0}); return true;\"></a></div>,   
         HttpUtility.HtmlEncode("'"+personnelPhotoList[j].name.Trim()+"'")));

Upvotes: 1

user2387092
user2387092

Reputation: 11

Somehow it did not post complete code, here it is again

strPhotos.Append(String.Format("<input type=\"button\" onclick = \"Delete({0}) return false;\", HttpUtility.HtmlEncode("'"+personnelPhotoList[j].name.Trim()+"'")));

Upvotes: 0

BenM
BenM

Reputation: 53208

The problem is that if you don't wrap the argument in quote marks, JavaScript is looking for a variable of the same name. Since variable names cannot begin with number literals, you're receiving the error. Numbers alone will be passed in as integers.

You should use the following:

<div class="leftMenuItems" onclick="javascript:showResources('1234ABC');">Product Name</div>

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You are missing quotes

onclick="javascript:showResources('1234ABC');"

because 1234ABC is a string, while numbers don't need quotes

Upvotes: 2

Related Questions