user5409139
user5409139

Reputation:

onclick in html image tag - pass string value to javascript function

Code:

// inside for loop..

$("#tabs").append('<li><a href="#tab' + 1 + '">' + 1 + '</a><img src="/Images/pdf.png" onclick="test('1s')" /></li>');

function test(val) {
    alert(val);
    //return false;
}

Please see this code onclick="test('1s')". Is there any syntax wrong?. I am not able to pass the value 1s to the test function.

But I can pass the value if it is 1 instead of 1s.

UPDATE:

How to pass a variable value...Lets say 1s is in variable val.. If I put onclick="test(\'val\')", I am getting the val as "val" instead of 1s

SOLUTION:

I solved myself..Refer to https://stackoverflow.com/a/32945494/5409139

Upvotes: 0

Views: 1080

Answers (4)

user5409139
user5409139

Reputation:

I got the solution. I added the quotes accordingly.

var val = "1s";
$("#tabs").append('<li><a href="#tab' + 1 + '">' + 1 + '</a><img src="/Images/pdf.png" onclick="test(\'' + val + '\')" /></li>');

Upvotes: 0

Tim Hong
Tim Hong

Reputation: 1

This is simple bug. Please do following...

$("#tabs").append("<li><a href='#tab" + 1 + "'>" + 1 + "</a><img src='/Images/pdf.png' onclick=\"test('1s')\" /></li>");

function test(val) {
    alert(val);
}

Upvotes: 0

cxw
cxw

Reputation: 17051

The code is in a single-quoted string argument, so the '' around 1s take you out of the string and back to the argument of the append function call. Try test(\'1s\') (backslashes before each quote mark) instead.

More details of JavaScript strings are, e.g., here.

Upvotes: 1

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12892

You should escape single qoutes: ' with a \ symbol.

$("#tabs").append('<li><a href="#tab' + 1 + '">' + 1 + '</a><img src="/Images/pdf.png" onclick="test(\'1s\')" /></li>');

Upvotes: 3

Related Questions