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]);
}
Related
My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
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 write a form that inserts some xml tags into textarea. I use this function:
(function ($) {
addCustomTag = function (name, param, value) {
var code = "<" + name + " " + param + "=\"" + value + "\">\n</" + name + ">";
document.getElementById("codeArea").value += code;
};
})(jQuery);
How can I make that some other function will insert subtags into tags that were created before?
XML code will never be used on server. All I need is to insert tex in specific line which is depends on what was on this line before not cutting it. Something like this:
addCustomSubtag = function(name,param,value,parent) {
document.getElementById("codeArea").selectionStart = document.getElementById("codeArea").value - parent.length;
var code = "<" + name + " " + param + "=\"" + value + "\">\n</" + name + ">";
document.getElementById("codeArea").value += code;
};
Javascript isn't necessary. It also can be written on jQuery.
Thanks.
You can any of these jQuery functions
http://api.jquery.com/append/
http://api.jquery.com/appendTo/
http://api.jquery.com/prepend/
Update:
Actually we can use jQuery DOM manipulation methods to manipulate XML also.
var xml = "<main/>";
alert(xml); // <main/>
var $xml = $(xml).append($("<sub1/>"));
alert($xml.html()); // <sub1></sub1>
$xml.find("sub1").append($("<sub2/>"));
alert($xml.html()); // <sub1><sub2></sub2></sub1>
alert($xml.get(0).outerHTML); // <main><sub1><sub2></sub2></sub1></main>
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"));
}