I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}
I have the following code:
$("#stats-list")
.append("<li>Elapsed: " + ajaxElapsed + "</li>\n" +
"<li>Display: " + tableElapsed + "</li>\n" +
"<li>Total: " + (ajaxElapsed + tableElapsed) + "</li>");
This was originally three appends that I concatenated into one. Is there anything I could do with jQuery that would clean up this code even more. What I was wondering was if jQuery has any string formatting with tokens that I could use.
function format(formatString) {
var args = Array.prototype.slice.call(arguments,1);
return formatString.replace(/\{(\d+)\}/g, function(match, num) {
return args[Number(num)];
});
}
format("<li>Elapsed: {0}</li>\n<li>Display: {1}</li>\n<li>Total: {2}</li>",
ajaxElapsed, tableElapsed, ajaxElapsed + tableElapsed);
afaik there is none built-in, but a powerful templating-subsystem, see jQuery Templates
just for completeness, i think this could be done more elegant:
var list = $('#stats-list');
$('<li />').text('Elapsed: ' + ajaxElapsed).appendTo(list);
$('<li />').text('Display: ' + tableElapsed).appendTo(list);
$('<li />').text('Total: ' + (ajaxElapsed + tableElapsed)).appendTo(list);
If you have many items you can do something like this to avoid missing + and writing li so many times. You can add any number of items inside the array and they will be joined with lis appropriately.
var list = '<li>' + [
'Elapsed: ' + ajaxElapsed,
'Display: ' + tableElapsed,
'Total: ' + ajaxElapsed + tableElapsed
].join('</li><li>') + '</li>';
$("#stats-list").append(list);
As a note I wouldn't use \n. li is a block element by default, so you'd be better styling it with css.
I'm trying to get the value of an input, but I can't have this:
$('#inputID').val();
Inside a seperate variable.
I have the following code:
var click = "$('#highlight"+n+"').replaceWith('<span id="+id+ " style="+c+">" + $("#input" + n + "").val() + "</span>');$('#black"+n+"').hide();$('#replace_box"+n+"').remove();";
This variable is not receiving the value of the input.
Can you explain to me why the following will not work?
$('#highlight"+n+"').replaceWith('<span id="+id+ " style="+c+">" + $("#input" + n + `"").val() + "</span>');`
And can I please get a solution. Cheers.
I try some mind reading but this code won't work because you have wrong quotes:
$("#highlight"+n).replaceWith("<span id="+id+" style="+c+">"+$("#input" + n).val() +"</span>");
in any case this code would be better:
var span = $('<span />', {id: id, style: c});
span.html($("#input" + n).val());
$("#highlight"+n).replaceWith(span);
I'm using Raphael for drawing some elements on a website. The elements include rectangle, line (path). I have given an id to the path element and trying to access it in the onclick event of that line. but when I do an alert of the id, nothing is visible. Following is the code snippet
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
t.node.onclick = processPathOnClick;
}
function processPathOnClick()
{
alert($(this).attr("id"));
}
Can anyone please tell me what is the problem with the above code. Any pointer will be helpful.
Thanks
Are you sure you don't want to write $(t.node).attr('id','Hello'); instead?
Update: someone just downvoted this answer. And I truly feel obligated to point out this way of setting the id isn't particularly good. You would be better off using:
t.node.id = 'Hello';
I wish there was a way to credit Juan Mendes, other than upvoting his comment to this answer.
Try this:
function createLine() {
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.id = 'Hello';
t.node.onclick = processPathOnClick;
}
function processPathOnClick() {
alert($(this).id);
alert(this.id); // This should work too...
}
Basically you are creating a new property called "id" on your Raphael line instance variable "t". It's kind of hacking, in my opinion, but it does the trick just fine.
Try setting the handler using jquery
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
$(t.node).click(processPathOnClick);
}
function processPathOnClick()
{
alert($(this).attr("id"));
}
Hey all, i have been trying for a few minutes on this problem and i can not seem to figure out how to correct it. I tend to have the hardest time doing stuff like this when it involves more than one varable within the function.
Here is the code:
var tempString = "thePrompt('Are you sure you wish to delete this?', 'theDel('" + IDnum + "', '" + theTitle + "', \'" + temperDay + "\', \'" + temperMonth + "\', \'" + temperYear + "\', \'" + DDiff + "\')";
html +=
"<div id='theTable" + IDnum + "' class='fc-event fc-event-hori fc-corner-left fc-corner-right' style='position:absolute; margin-top: 15px; z-index:8;left:"+left+"px'><div id='apDEL' style='position:relative;width:0px;height:0px;z-index:1000; top:-13px; left:2px; float:left;'><img src='img/xCal.png' width='15' height='15' alt='' border='0' onclick=\"" + tempString + "\" /></div>" + (ETC ETC...)
The error i keep getting is this:
Error: missing ) after argument list
Line: 1, Column: 68
Source Code:
thePrompt('Are you sure you wish to delete this posting?', 'theDel('105', '50 points for visiting us today!!!!', '13', '3', '2010', '2')
And its pointing to the '105'.
As always, any help would be wonderful! :o)
David
EDIT/UPDATE
Ok, so now i have moved some things around and i got it working (that is sending the values to the popup prompt box BUT for some reason it doesn't see my function after i hit the delete button! This is because the prompt is on the main page and the code i am working with is inside a iframe.
function theDel(theID, theTitle, day, month, year, DDiff)
{
var tempString = "delClientE(" + theID + ", '" + theTitle + "', " + day + ", " + month + ", " + year + ", " + DDiff + ")";
parent.thePrompt('Are you sure you wish to delete this event?', tempString);
}
The delete button values now look like this:
delClientE(110, 'sadfsadfsdf', 14, 3, 2010, 2); jQuery.prompt.close();
However, even putting parent.delClientE doesnt find the function either... How can i call it from within the iframe when the prompt box is outside of that?
David
Keeping track of escaping in nested contexts is really hard, and because when you get it wrong you've very often given yourself a script-injection security problem, it's much better to avoid creating HTML/JS by sticking strings together.
Instead, use DOM methods to assign your event handler from JavaScript and say goodbye to all that irritating backslash and quoting stuff:
var img= document.createElement('img');
img.src= 'img/xCal.png';
img.width=img.height= 15;
img.onclick= function() {
if (confirm('Are you sure you wish to delete this?'))
theDel(IDnum, theTitle, temperDay, temperMonth, temperYear, DDiff);
};
div.appendChild(img);
it's because of the quotes here 'theDel('" + you should escape the inner single quotes.
Edit. that is of course, in addition of the missing right paren issue already on the table. :)
I think it's missing at the end of the statement .. your statement looks like this:
var tempString = "thePrompt('question', theDel(params)";
.. where it should have one more closing ')' at the end.
and one more thing you might want to look at is the fact that the arguments in theDel are wrapped in single quotes.
thePrompt('Are you sure you wish to delete this?', 'theDel('105', '50 points for visiting us today!!!!', '13', '3', '2010', '2')' )
And that might be a problem since the params in thePrompt are also wrapped in single quotes so I would make the thePrompt have double quotes arround it's params so it would look something like this:
var tempString = "thePrompt(\"Are you sure you wish to delete this?\", \"theDel(\'" + IDnum + "\', \'" + theTitle + "\', \'" + temperDay + "\', \'" + temperMonth + "\', \'" + temperYear + "\', \'" + DDiff + "\')\")";
David, not sure if this has been answered to your satisfaction yet, but it might be easier to create a temporary variable for this:
var theDel = "theDel('" + IDnum + "', '" + theTitle + "', '" + temperDay + "', '" + temperMonth + "', '" + temperYear + "', '" + DDiff + "')";
var tempString = "thePrompt('Are you sure you wish to delete this?', \' + theDel + \')";
First of all, you'd be far better using event delegation with the js library of your choice.
Failing that, a string interpolation function makes these sorts of things easier:
String.prototype.format = function(values) {
return this.replace(/\{(.+?)\}/g, function(s, key) {
return values[key];
});
}
So long things like this become:
var s = 'blah blah blah "{IDnum}" blah blah blah \'{foosball}\''.format({ IDnum: '1', foosball: 'xyz'});
(If you don't like manipulating String's prototype, you can put the function somewhere else.)
Ok, how about this?
iFrame source
<html>
<head>
<script type="text/javascript">
function localDel(params){
if (window.parent && typeof window.parent.thePrompt==='function')
window.parent.thePrompt('Are you sure you wish to delete this event?', params);
}
</script>
</head>
<body>
<p onclick="localDel([1,'some title', 14, 3, 2010, 2])">delete</p>
<p onclick="localDel([2,'another title', 14, 3, 2010, 2])">delete</p>
</body>
</html>
Parent source
<html>
<head>
<script type="text/javascript">
function thePrompt(msg,params) {
if(confirm(msg)) theDel.apply(this,params);
}
function theDel(id, title, tDay, tMonth, tYear, dDiff) {
alert(id);
// etc...
}
</script>
</head>
<body>
<iframe src="iframe.html" />
</body>
</html>
I finally got it!! YAY! :o)
function theDel(theID, theTitle, day, month, year, DDiff)
{
var tempString = "window.frames.theCal.delClientE(" + theID + ", '" + theTitle + "', " + day + ", " + month + ", " + year + ", " + DDiff + ")";
parent.thePrompt('Are you sure you wish to delete this event?', tempString);
}
I needed the window.frames.theCal in order to call my function. theCal is my iframe id.
David