I'm appending some html codes on javascript. I'm also binding an onclick to it. The problem is, I'm getting a javascript error each time I press onclick. I'm passing a string to the function onclick. Here's a clearer view.
var propertyTypeDdlValues = "";
propertyTypeDdlValues += "<li onclick='selectPropertyType('Condominium/Studio')'>Condominium/Studio</li>";
$("#propertyTypeDdl").html(propertyTypeDdlValues);
This is my selectPropertyType
function selectPropertyType(cattype){
$("#propertyType").text(cattype);
$("#hdnPropertyType").val(cattype);
}
I keep on having this error:
Uncaught SyntaxError: Unexpected token }
I think the problem is how I wrap strings around (" "). What made me say this? Because when I try to just use a simple function like this:
propertyTypeDdlValues += "<li onclick='displayMessage()'>Condominium/Studio</li>";
function displayMessage(){
alert("Message");
}
It goes through the function and the alert message is being displayed.
Any ideas? Thanks!
Here is a solution:
JSFiddle
$(function () {
$("#propertyTypeDdl").append("<li onclick=
selectPropertyType('Condominium/Studio')>Condominium/Studio</li>");
$("#propertyTypeDdl").append("<li onclick=
'displayMessage()'>Condominium/Studio</li>");
});
function selectPropertyType(cattype) {
$("#propertyType").val(cattype);
}
function displayMessage() {
alert("Message");
}
One way would be to store that string in a variable and passing that into the function. But I guess some one else will give a better answer.
Modify your propertyTypeDdlValues to
propertyTypeDdlValues +=
"<li onclick='selectPropertyType('\'Condominium/Studio\'')'>
Condominium/Studio
</li>"
You are using jQuery.
So why not:
foreach(thing in listOfThings) {
var li = $('<li>' + thig.name + '</li>');
li.click(function(e) {
selectPropertyType($(this).html());
});
$("#propertyTypeDdl").append(li);
}
It's a lot cleaner.
Friendly advice: never ever use HTML on/whatever events again :)
Your original string
"<li onclick='selectPropertyType('Condominium/Studio')'>Condominium/Studio</li>"
Gets parsed as this HTML:
<li onclick='selectPropertyType('Condominium/Studio')'>Condominium/Studio</li>
The onclick atrribute ends just after the left bracket, leading to invalid javascript. Since you have three levels of nesting, you'll need to escape your quotes:
"<li onclick='selectPropertyType(\'Condominium/Studio\')'>Condominium/Studio</li>"
or
"<li onclick='selectPropertyType(\"Condominium/Studio\")'>Condominium/Studio</li>"
but it is better to avoid pieces of javascript code as strings (and, since you're using jQuery, avoid onclick attributes altogether), and create an element and set its click handler to a function. This will also avoid the need to nest string literals:
var $li = $("<li>").text('Condominium/Studio').click(function(){
selectPropertyType('Condominium/Studio')
});
$propertyTypeDdlValues = $propertyTypeDdlValues.add($li)
Related
I Tried this code to get multiple value in href but it does not work. any problem on this one ?
Print
You are missing a + sign between a string and a value.
The error is between this two
document.getElementById('CUS_CODE_MX').value '&AGE='
Correct format
document.getElementById('CUS_CODE_MX').value + '&AGE='
Every time you join a value and a string, you need a + sign
Even if you are joining two strings
'Hello'+ 'World'
Pliss avoid long js as an inline atribute. I will recommend you call a function as the onclick attribute.
Hope this helps :)
Print
It's better to use external script for that rather than inline format. And just add missing + to your code. Also, using variables would clean up the code.
function func() {
var CUS_CODE_MX = document.getElementById('CUS_CODE_MX').value;
var AGEID = document.getElementById('AGEID').value;
this.href = 'printsales.php?CUSTOMERID='+CUS_CODE_MX+'&AGE='+AGEID;
}
Print
I'm having a bit of trouble correctly displaying a message in a webpage I am trying to create. The code I have is:
content.innerHTML += "<button 'onclick=\"likeFunction(" + feed.messages[y]._id + ")\">" + "Like(" + feed.messages[y].likesCount + ")" + "</button>"
When I inspect the element on the page source, I get this output:
<button 'onclick="like(idOfObject)">Likes(likeNumber)</button>
What I need it to look like is:
<button 'onclick="like("idOfObject")">Likes(likeNumber)</button>
I'm a bit confused on how I would add more single or double quotes and where to escape them correctly to get this desired output.
I think I see a few typos. Most noticeably with the leading ' in front of onclick. I don't think this needs to be here.
As for formatting the string, consider looking into template literals introduced in ES6.
Might look something like this:
content.innerHTML += `<button onclick="likeFunction(${idOfObjectVariable})">Likes (${likeCountVariable})</button>`
Hope this helps
You're so close! First, you need to remove the ' before onclick. If you want to add double quotes around the idOfObject, then you just need escape one double quote after likeFunction( and one double quote before )\">".
"<button onclick=\"likeFunction(\"" + feed.messages[y]._id + "\")\">"
The only problem is that when the double quotes around your variable idOfObject render, they'll correspond to the opening and closing quotes you already have for onclick. So, your solution should have single quotes inside of double quotes:
"<button onclick=\"likeFunction(\'" + feed.messages[y]._id + "\')\">"
I would have guessed what you wanted in your HTML would be:
<button onclick="like('idOfObject')">7</button>
or
<button onclick='like("idOfObject")'>7</button>
You probably do not want to quote the entire on-click attribute, just the part on the right hand side of the = .
content.innerHTML += "<button onclick=\"like('" + feed.messages[y]._id + "')\">" + ...
I'm guessing you also probably don't want something that gets displayed to the user that looks like a function all, but the result of the function call, but that is not what you were asking about.
You SHOULD NOT concatenate html manually from untrusted input (suppose someone injected malicious html code to your feed.messages[y]._id or another field). Sanitization is one of your options but it's like patching a huge hole.
You can read more about preventing those security attacks named XSS here.
Consider creating your DOM manualy with createElement API and bind your event handlers manually.
function renderButton(content, feed, y) {
function likeFunction() {
alert("LIKE" + feed.messages[y]._id);
};
var button = document.createElement("button");
var text = document.createTextNode("Like(" + feed.messages[y].likesCount + ")");
button.appendChild(text);
button.addEventListener('click', likeFunction)
content.appendChild(button);
}
Then you can just render your button with a simple function call.
renderButton(content, feed, 0)
I am using JavaScript to create a button element and binding onclick event to it. I am using the below code:
function getElement (rowObject )
{
var element ='<div id="deptNmBtn"><button onClick=getDepartMentNm("' + rowObject.empName+'")> <span>Add</span></button></div>';
return element;
}
But here I am passing a parameter Employee Name. The code works if employee name is passed as a single string without any spaces but when passed with spaces its throwing JavaScript error.
SyntaxError: unterminated string literal
Have anyone faced this error? Any help will be really appreciated.
You need to wrap the inline click handler with ':
function getElement (rowObject) {
var element = '<div id="deptNmBtn"><button onClick=\'getDepartMentNm("' + rowObject.empName + '")\' ><span>Add</span></button></div>';
return element;
}
DEMO.
There is a quoting problem in your code. Try this:
var element = '<div id="deptNmBtn"><button onClick="getDepartMentNm(\'' + rowObject.empName + '\')" ><span>Add</span></button></div>';
As you can see, the value for onClick is unquoted. Browsers can parse unquoted attributes, but then they are expected to end up to a space. Actually your parsed code looks like this:
<button onClick=getDepartMentNm("Employer Name")>
HTML parser cuts the function call from the first space, and Name") is ignored since it can't be regognized as valid HTML. JavaScript is executed from "right to left", and the first thing JS tries to do is to get a valid string for function argument. Now HTML parser has cut the function, and JS can't find closing quote, so it throws an error.
I'm only just learning javascript so I imagine this is relatively simple but it's been annoying me for a while now.
I have a function that simply displays some text that I am calling from a AJAX response. Here's my code.
if(this.responseText != null)
{
var text = "<ul>";
var object = eval("(" + this.responseText + ")");
var track;
for (var i = 0; i < object.length; i++)
{
track = object[i];
text += "<li><img src=\"" + track.artwork_url + "\"/>";
text += track.title;
text += "<ul><li>Play</li>"
text += "<li>Download</li></ul>"
text += "</li>";
}
text += "</ul>";
document.getElementById("content").innerHTML = text;
}
function playTrack(track)
{
document.getElementById("content").innerHTML = "This has worked";
}
It's not liking me passing the track object to the function playTrack (a simple function for now that just displays some text). I get the error "Uncaught SyntaxError: Unexpected identifier"
If I pass in track.id (or any other property), it all works fine which I don't understand.
Thanks for any help,
Mister B.
You cannot pass an object like this. track is getting converted to a string and then your playTrack function call fails because the syntax is wrong. It'll be rendered (something like onclick=playTrack([Object object]) which clearly isn't valid JavaScript). What's wrong with just passing the track.id since you know that works?
The #alpian and #Jim is right, you need convert the object to json string, you can use http://www.json.org/js.html to this.
...
text += "<ul><li>Play</li>"
...
When creating the "playTrack" onclick event, you are using the track variable in the wrong way. "track" is an object, and using it as a string will be [Object object]. So in your "html" you'll have something like onclick="playtrack([Object object])" and this is syntactically wrong.
I'd strongly suggest the use of JSON.parse() instead of eval. Instead of building your list entries as text I'd make them as DOM objects with document.createElement() and add the click handlers as addEventListener, that way you wouldn't have the need to try to include your JS objects as text in the HTML stream.
I have the following code, written using jQuery:
var strval = '22'
$("#quicknote").attr("href",
"javascript:location.href=/'http://site.com/notes/add?projects=/'+ strval")
Which results in the following attribute:
<a href="javascript:location.href='http://site.com/notes/add?projects='+'strval'"
id="quicknote">
But, what I want is:
<a href="javascript:location.href='http://site.com/notes/add?projects='+'22'"
id="quicknote">
Any jQuery wizards know how I might achieve this result?
Try:
var strval = "22";
$("#quicknote").attr("href",
"javascript:location.href='http://site.com/notes/add?projects=" + strval + "'");
Note the position and type of quotes.
On a side note, I'm not exactly sure why you wouldn't to do this instead:
var strval = "22";
$("#quicknote").attr("href",
"http://site.com/notes/add?projects=" + strval + "'");
ie theres no need for Javascript in your example.
Lastly, since you are using jQuery anyway I wouldn't put Javascript in the href like this either. Instead add a click() handler:
$("#quicknote").click(function() {
window.location = "http://site.com/notes/add?projects=22";
return false;
});
A JQUERY wizard tells you, that it is possible, but it has just nothing to do with jQuery, and that your answer is:
You have the quote wrong!
And there is no reason to vote me down, because I answered the initial question in very, very, very professional style.