jquery replaceWith mixture of quotation marks ' and " - javascript

I have written a few lines of JQuery code that replaces an item on a list from a link to log in, to a link to log out and vice versa. It also scrolls the page back to the top. I've had to use a mixture of single quotation and double quotation marks. Clearly, this code:
$('#myntamsloti').replaceWith("<li id="myntamsloto">LogIn</li>");
gives an error as the first set of quotation marks are interpreted as the end of the statement. Switching them around lengthens the command but I can't find a combination that allows the whole line to be run. So, I've chopped the line up:
var htmlinsert = '<li id="myntamsloto"><a href="#" onClick="javascript: ';
htmlinsert = htmlinsert + "$('html, body').animate({scrollTop:$('#login').offset().top}, 600);";
htmlinsert = htmlinsert + '">LogIn</a></li>';
$('#myntamsloti').replaceWith(htmlinsert);
It works but I've never seen this.
Is there a more elegant way of doing it?

You can amend your single line of code using replaceWith() to use the correct quotes. You need to use different quotes to delimit the string and the attributes within it, and then escape the inner quotes where they must match those delimiting the string. Try this:
$('#myntamsloti').replaceWith('<li id="myntamsloto">LogIn</li>');
That said, the HTML would be much simpler (and better practice) to omit the outdated onclick attribute in the HTML to be inserted and attach an event handler using JavaScript, like this:
$(document).on('click', '#myntamsloto', function(e) {
$('html, body').animate({
scrollTop: $('#login').offset().top
}, 600);
});
$('#myntamsloti').replaceWith('<li id="myntamsloto">LogIn</li>');

How about doing it a programmatically friendly way..
Yes it's more lines of code, but it has the added benefit that you can do a LOT more with the objects defined, and you can use scoped variables in the click handler AND your inspect source will be a lot cleaner.
$myntamsloto = $('<li id="myntamsloto">');
$myntamslotoLink = $('LogIn');
$myntamslotoLink.on('click',function() {
$('html, body').animate({
scrollTop: $('#login').offset().top
},
600);
});
$myntamsloto.append($myntamslotoLink);
$('#myntamsloto').replaceWith($myntamsloto);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="login">login</button>
<div style="height:800px;background:green;width:20px;clear:both;"></div>
<ul>
<li>foo</li>
<li>bar</li>
<li id="myntamsloto">baz</li>
</ul>

Related

Alternating between single and double quotes indefinitely

I'm having an issue dealing with multiple embedded/alternating quotes that I'm hoping someone can help with. Here's the relevant code...
displayMessage(
"post success!",
"<p style='margin-top: 15px; margin-bottom: 15px'>if you'd like to share your post...</p>
<a onclick='openSharePopup("+textA+","+numberA+","+numberB+")' style='cursor: pointer; font-size:16px'>
share
</a>"
);
function displayMessage(heading, text){
$("#displayMessageHeadingDiv").html(heading);
$("#displayMessageBodyDiv").html(text);
$("#displayMessageParentDiv").css("display","block");
}
displayMessage() is called after the user successfully posts something on the website, and works perfectly unless "textA" contains an apostrophe (e.g. something like "Mike's Opinion")
The problem being (I think) is that although textA is encapsulated inside double quotes - those double quotes are already inside the single quotes of my onclick attribute - which itself is inside yet more double quotes of the entire second argument of displayMessage.
I thought previously that alternating between single and double quotes could continue indefinitely but this example seems to suggest otherwise. I've also experimented with these alternatives to break any quotes in textA but neither have worked...
textA = JSON.stringify(textA).replace(/&/, "&").replace(/"/g, """);
textA = textA.replace("'","\'");
Any ideas on where I'm going wrong with this?
Your approach is fundamentally wrong. Manually creating inline event handlers is almost always the wrong way to do it.
A better solution would be for example:
var shareLink = $( '<a>share</a>' )
.css({ cursor: 'pointer', 'font-size': '16px' })
.click( function() {
openSharePopup( textA , numberA, numberB );
});
var msg = $( "<p>if you'd like to share your post...</p>" )
.css({ 'margin-top': '15px', 'margin-bottom': '15px' });
displayMessage( "post success!", shareLink.add( msg ) );
function displayMessage(heading, text){
$("#displayMessageHeadingDiv").html(heading);
$("#displayMessageBodyDiv").empty().append(text);
$("#displayMessageParentDiv").show();
}
Essentially you should create the elements, add a click handler through the code, and add the elements directly to the container. This way you don't have to think about what kind of quotes to use and where.
(As another stylistic side note, it would be much better to use CSS classes to style the elements instead of inline styles.)

htmlencode a string in javascript

Hello I have a function that loops around and then eventually a string gets sent to a DIV tag class...
$(document).ready(function addcopy() {
/* global */
$(".Bands").append('<div style="display: inline-block;">[EDIT] <h7 style="color:#7A0029;line-height: 110%;text-transform: uppercase;">[Custom:Name]</h7> </div>');
});
It works fine... however the token [Custom:Name] may contain special characters such as single or double quotes etc...
I've looked around these forums and tried to adapt my code to various solutions offered and it never seems to work, could somebody help me?
Thanks for your help!
Alex
EDIT(1):
Getting somewhere, from Ockert's and LeFex's answer I've adapted it below but it still does not work (replace speech marks and special characters from token which html can't handle)...
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function (){
/* global */
var band = $("<div style='display: inline-block;'>[EDIT] <a href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.appendTo(htmlEncode('.Bands'))
});
You can change your script too
$(document).ready(function (){
var band = $("<div style='display: inline-block;'>[EDIT] <a class='link' href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.find('.name').html("some weird name !##$%^&*");
band.find('.link').attr("href","http://www.google.com");
band.appendTo('.Bands');
});
By splitting it up like that, enables you to set the name to anything you want. You can easily select the name element
Have a look at this jsfiddle http://jsfiddle.net/fL3gn056/2/
You could use document.createElement instead of just appending a string.
http://www.w3schools.com/jsref/met_document_createelement.asp
If you just create your div, a and h7-elements, use the appendChild function, and add style and attributes and content by setting element properties, you should end up with a sollution that allows any special characters.
Edit:
I could'nt get it working using that method; however, with the approach I suggested above, i got some working code:
var element = document.createElement("div");
element.style.display = "inline-block";
var link = document.createElement("a");
link.setAttribute('href', "[LINK]");
var text = document.createElement("h7");
text.style.color = "#7A0029";
text.style.lineHeight = "110%";
text.style.textTransform = "uppercase";
text.innerHTML = "[CUSTOM:NAME]";
//not sure what you're appending it all to, but do it here
document.getElementsByClassName("Bands")[0].appendChild(element);
element.appendChild(link);
link.appendChild(text);
With this snippet, all input special characters are interpreted as a string, not as code. Some calls I could have put in the same line, but this way you get an easy to read overview.
Here's an earlier thread on the subject, and the top answer brings the issue of performance of different approaches to discussion.
jQuery document.createElement equivalent?

Jquery, Escaping url with variable

trying to escape and html for appending in jquery with adding a dynamic variable that i am bringing in with ajax and I seem to not be able to get the escaping correct. Here is what I have -
$("<div><div class='presiImg' style='background: url(/\'/gleam\/public\/images\/itPrecedents\/" + keep.logo + "');'></div></div>").appendTo(".myDiv');
I am unsure how to escape this correctly so I can use the variable. Thanks.
You've got a couple issues here:
You're escaping the forward slashes in your URL and that is not necessary
You are using inconsistent quotes in your .appendTo()
As a suggestion, when I append raw HTML using JS/jQuery I try to use the single-quote and the JavaScript quote, and then use the double-quotes in the HTML. For me it is just easier to see that way. Also, the single-quote in the CSS url is not required, and is perhaps confusing the matter.
Anyway, if you change your line to the following it will work:
$('<div><div class="presiImg" style="background: url(\'/gleam/public/images/itPrecedents/' + keep.logo + '\');"></div></div>').appendTo('.myDiv');
There is a runnable example below if you want to see it in action:
$(function() {
var keep = { logo : "test.jpg" };
$('<div><div class="presiImg" style="background: url(\'/gleam/public/images/itPrecedents/' + keep.logo + '\');"></div></div>').appendTo('.myDiv');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myDiv"></div>
try
$("<div />",{
"class":"presiImg",
"style":"background: url(/gleam/public/images/itPrecedents/"+keep.logo+")"
}).appendTo(".myDiv");

Escape quotes in Javascript function

I'm trying to use a href onclick event in kendo grid template. When I click on the link I need the alert to diplay path text but it gives "PDF undefined error". I think it could be an issue with escape quotes.
${PDF} returns a string value.
template: "<a id='${PDF}' class='clsPDF' onclick='setpdf(\${PDF});' href='\\#'>View</a>"
<script>
function setpdf(path)
{
alert(path);
}
</script>
I would suggest slightly different approach. Instead of using inline function you can use a delegate function attached to your Grid element which will take care of all buttons like the one you defined in the template.
e.g.
$("#gridName").on("click", ".clsPDF" , function(){
var model = $("#gridName").data("kendoGrid").dataItem($(this).closest("tr"));
alert('you clicked on item with id' + model.TheIdProperty);
})
I hope this gives you the idea. I think it is cleaner this way.
When the browser looks at the link make sure it sees it like this:
<a id='someId' class='clsPDF' onclick='setpdf("pdf.pdf");' href='#'>View</a>
If it sees it like this:
<a id='someId' class='clsPDF' onclick='setpdf(pdf.pdf);' href='\\#'>View</a>
It will think pdf is a javascript object/variable and try and use it.
So you are right it is most likely a problem with quotes. You could try wrapping your \${PDF} with escaped double quotes:
\"\${PDF}\"

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

Categories