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);
Related
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 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 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"));
}
I'm having a bit of a problem escaping quotes in the following example:
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');
The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:
onkeyup="runFunction(" #row2="" );=""
What exactly am I doing wrong?
Just don't put JavaScript into the HTML string:
$(id).html(
'<td><input type="text" id="my' + newId + '"></td>'
).find("input").keyup( function() {
runFunction("#my" + newId);
});
Thinking about it, in this special case you can exchange the keyup() function body for:
runFunction(this);
because you seem to want to run the function on the object itself.
You need to use HTML character references for HTML attribute values. Try this:
function htmlEncode(str) {
var map = {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"};
return str.replace(/[&<>"']/g, function(match) { return "&" + map[match] + ";"; });
}
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="' + htmlEncode('runFunction("#my' + newId + '");') + '"></td>');
You forgot to escape the attribute's quotes.
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction(\'#my' + newId + '\');"></td>');
You should use escaped single quotes \' to surround the #my... part.
I have this <ul>
<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>
This javascript code which is meant to go throug a JSON object and add the options
to the UL:
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
});
If I do console.log() I can see that the looping is working. If I do:
console.log($("#select_opts").html());
It shows the HTML being updated as expected. However in the browser window, it shows the
UL as empty!
What am I doing wrong?
$("select_opts").append(str);
should be
$("#select_opts").append(str);
you're referring to object by id so you missed #
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
// ^
}
I can't really see what's wrong, but try this instead, just to see if it works...
$(str).appendTo("#select_opts");
Both should work.
Is this a typo?:
$("select_opts").append(str);
Did you mean?:
$("#select_opts").append(str);
UPDATED:
Try this:
$.each(q.opts, function(i, o) {
var li = $('<li>').attr('id', 'li_' + i);
var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
li.append(in).append(aa)
$("#select_opts").append(li);
});
The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.
I'd imagine input needs to be properly self-closed.
I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.