Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quote a string dynamically in Javascript?

Tags:

javascript

This kinda funny, i want to quote a string value for a function but javascript throws this error Uncaught SyntaxError: Unexpected token }

This my code

var val = "Testing String";
var table_row = "<tr><td><a href='#' onclick='test('"+val+"')'>Row1</a></td></tr>";

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

The table row get created fine with the test function bound well with onClick event. But when i click on the created link i get

`Uncaught SyntaxError: Unexpected token }

The Value within the test function should be a quoted string.

Note: If i remove the concatenation of the val string, and pass is as a string like this

table_row = "<tr><td><a href='#' onClick='test(\"Testing String\")' >Row1</a></td>";

... it works

Where am i goofing?

Gath.

like image 451
gath Avatar asked Jun 25 '26 20:06

gath


2 Answers

Then in your original script also escape ":

var test = "\"test string\"";
like image 180
Saeed Neamati Avatar answered Jun 27 '26 11:06

Saeed Neamati


i thing it ll help u sir,,,,

if row1 is variable

u can add by '+Row1+' seperator,

or else directly use bellow code;

var table_row = '<tr><td><a href="#" onClick="test(\'Testing String\')" >Row1</a></td>';
        //alert("++++++++++++"+table_row+"++++++++++++");

see ya ,,,

like image 30
K6t Avatar answered Jun 27 '26 09:06

K6t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!