Passing parameter as string containing white spaces in javascript onclick function
"<button onclick=editRecords('" + partId + "')>Add Quantity</button>";
If I pass in a string partId
without spaces it works fine. But if I get through 'MRF 01'
it will give me
Unprepared SyntaxError: Unexpected ILLEGAL token.
Why is this and how can I fix it?
Use
whenever you pass a space as a parameter to a function. If you are using js to generate onclick use encodeURIComponent.
"<button onclick=editRecords('" + encodeURIComponent(partId) + "')>Add Quantity</button>";
From the author himself. This is primarily an opinion based answer, there is nothing common about using single quotes (I discovered C syntax and now I prefer double quotes ...).
I would prefer to change the organization of the quotes to get cleaner code. This will make it more readable as well as more familiar (in my opinion):
var msg = 'Sometimes SO looks like a McDonalds drive through.';
var html = '<button onclick="clickHandler(\'' + msg + '\')">click me</button>';
function clickHandler (msg) { alert(msg); }
document.body.innerHTML = html;
It would be even more conditional to follow the wisdom of Felix Kling (last line).
If the HTML attribute value must contain a space, you need to use quotation marks to delimit the value.
Pay attention to the syntax:
<span foo=bar baz ></span>
It is an attribute foo
with a value "bar"
and a boolean attribute baz
.
On the other hand, it is
<span foo="bar baz"></span>
is an attribute foo
with a value "bar baz"
. Notice how it baz
stands out differently?
To fix your problem, put quotes around the value onclick
or better, use a different way of binding your event handler .
I would suggest that this is the best option. You can set any attribute you want.
var e = document.createElement("span");
e.className = "close-li";
e.setAttribute('aria-hidden', 'true');
e.setAttribute('data-toggle', 'modal');
e.setAttribute('data-target', '#CreateModal');
e.setAttribute("onClick", "FunctionName(" + parameters + ");" );
e.innerText = "Γ";
$('#id').append(e); //Id would be the place where you want to append. I used jquery so, I used append
String parameters with spaces
<input type="button" onClick="return myFunction('10', 'your text hear')" />
or
PHP String Variables with spaces
<input type="button" onClick="return myFunction('<?php echo $id ?>', '<?php echo $designation ?>')" />
JS function
function setVisibility(id, designation) {...your js code hear...}