Alternating between single and double quotes indefinitely - javascript

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.)

Related

jquery replaceWith mixture of quotation marks ' and "

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>

How to add user input to a JavaScript array

I am in the process of learning JavaScript and jQuery, so apologies if any of this sounds naive or obvious. I started what I thought was a fairly simple project to practice and hopefully learn something in the process.
What I want to do is this: the user inputs a sentence and hits a submit button. The sentence gets added to a list of other sentences submitted by people (preferably on a separate file, preferably encrypted, but not necessary). Then, the website grabs a random sentence from the list and displays it.
I am not asking on how to build all of this. I have already put most of it together, but I am including it here for reference.
I have a separate javascript file with the array of quotes.
var quotes=new Array();
quotes[0]="<p>Quote 1</p>";
quotes[1]="<p>Quote 2</p>";
quotes[2]="<p>Quote 3</p>";
quotes[3]="<p>Quote 4</p>";
quotes[4]="<p>Quote 5</p>";
quotes[5]="<p>Quote 6</p>";
quotes[6]="<p>Quote 7</p>";
Then I randomly display one using this:
function getQuote(){
var thisquote=Math.floor(Math.random()*(quotes.length));
document.write(quotes[thisquote]);
}
And adding <script> getQuote(); </script> to the html.
This all works fine.
The part I cannot seem to figure out is taking user input and adding it to the jQuery array. I am using a contenteditable div instead of an <input> because I want it to have multiple lines of text and have a character limit, which as far as I know can only be done with a contenteditable div (according to the research I did at the time, I may be wrong).
I have looked around and tried many if not all the examples I found of how to do this, and none of them worked. This is the last method I tried, if it helps:
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
So, to reiterate, I want to take user input and add it to a JavaScript array. I have scoured stackoverflow and the interet but nothing has worked. Please help!
UPDATE: Arvind got it right. I still have a lot to learn, and it seems I need to read up on localstorage and cookies. I will also need to use PHP to save the sentences on the server. Thank you to all who answered!
Problem is document.getElementsByClassName("input") gives you a NodeList and not just a single html element. So if you do this document.getElementsByClassName("input").value, you will end up quotes as [undefined, undefined ... undefined]. Assuming you have single element with the class name input, go with index 0. Also as you stated that you are using div with attribute contenteditable, you may try this instead. document.getElementsByClassName("input")[0].innerHTML
Try this example.
var quotes = localStorage.getItem('quotes'); //get old, if any, gives you string
quotes = quotes ? [quotes] : []; // if got quotes then make it as array else make new array
$(function() {
var quote = $('#quote'); //get the quote div
quote.html(quotes.join('') || quote.html()); //set the default text
$('#btn').on('click', function(e) {
quotes.push(quote.html());
localStorage.setItem('quotes', quotes.join('')); //save the quotes
alert(quotes.join(''));
});
});
#quote {
border: 1px solid grey;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div contenteditable='' id='quote'>
<ol>
<li>Quote 1</li>
<li>Quote 2</li>
</ol>
</div>
<input type='button' id='btn' value='Submit' />
P.S.
In order to preserve the old quotes you may possibly use cookie, localStorage, etc.
Are these "quotes" being saved locally?
Yes, to share it among several users visiting by different browsers, you have to save it with the server script like PHP, Java, ASP, etc. Here you can either use ajax, if you wana avoid page reload on submit, else you can go for form submit.
$(".submit").click(function() {
quotes[quotes.length] = document.getElementsByClassName("input").value;
});
should be
$(".submit").click(function() {
quotes.push(document.getElementsByClassName("input").text());
});
EDIT: With a content editable div you need to use text() instead. Here is an example fiddle. https://jsfiddle.net/
var quotes=[];// better
// function to add to array
function addQuote(myquote){
quotes.push('<p>'+myquote+'</p>');
}
addQuote("Quote 1");
addQuote("Quote 2");
addQuote("Quote 3");
addQuote("Quote 4");
addQuote("Quote 5");
addQuote("Quote 6");
addQuote("Quote 7");
addQuote("Quote 8");
$(".submit").on('click',function() {
addQuote(document.getElementsByClassName("input")[0].value);
});
NOTE: suggest NOT using the "input" class name and use some other one as that might be confusing to others at some point later (confused by element named input)
I also added the paragraph tags as that would provide a consistent pattern for your input text. Assumption on my part however.
NOTE I also assume that the element IS an input type with the .value since that is NOT provided (the markup)

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}\"

Categories