Jquery, Escaping url with variable - javascript

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");

Related

how i can put <script> in double quote

I'm trying to add the script tag using JavaScript. I'm putting the tag into double quote.
My problem is something else but solves with this simple example:
<script>
document.write("<script>" + example_var + "<\/script>");
</script>
How can I fix it?
You can use two ways
Template Literals
document.write(`"<script>"${example_var}"<\/script>"`);
Single Quotes
document.write('"<script>"' + example_var + '"<\/script>"');

Generating id selector dynamically based on user-input

I am facing a problem in jQuery selector. I am generating selector string dynamically based on user-input as show below :-
jQuery("#" + userInput + "-edit").modal("show")
When the user enters value like "AdvancedResults." Selector becomes
jQuery("#AdvancedResults.-edit").modal("show")
which does not return expected element, despite the fact that
Am I doing something patchy ? Is there any better way to solve this problem ?
Btw, apologising for newbie question, as I am new to JS world.
Thanks in advance.
Just use:
Use the escaping rules from the jQuery selectors API as follows:
$("#AdvancedResults\\.-edit").modal("show");
You can replace . to \. dynamically using str.replace():
var str = "AdvancedResults.";
str = str.replace(/\./g, "\\."); // it will add add \\ dynamically before .
console.log($("#"+str+'-edit').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input id="AdvancedResults.-edit" type="text"/>
If your element does have an id #AdvancedResults.-edit, that is, includes a dot, you must escape it with \\ as stated in the docs jQuery Selectors
Use [attribute=""] selector in such cases where the parameter is dynamic and might contain special chars not supports by jQuery # - ID selector.
jQuery("[id='" + userInput + "-edit']").modal("show")
Example snippet :
var userInput = "abc.";
alert(jQuery("[id='" + userInput + "-edit']").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="abc.-edit" value="test"/>
I have solved it using attribute hack.
It's as follow :-
jQuery("[id='" + userInput + "-edit']").modal("show");
It worked perfectly for me.

Escaping forward slash ("/") while using JavaScript to change CSS class

I need to add some CSS class based on some condition using JavaScript but facing issue in case my string contains a forward slash (/). This is what my use case is
<div id="div_product-size-icon-121NM/L" class="disabled"></div>
<script>
var newProductCode = '121NM/L';
if( newProductCode.contains('/') ){
newProductCode = newProductCode.replace('/','/\//');
$('#'+'div_product-size-icon-'+newProductCode).addClass('active');
}
</script>
I have even tried newProductCode.replace('/','/\'); but while running code, I am facing following error
JavaScript error: SyntaxError: unterminated string literal
I can not change HTML along with product code; the option for me is to change it in JS.
Here is a working js example: JS code
I have first replaced the if statement with indexOf() and changed the .replace function as .replace('/', '\\/');
var newProductCode = '121NM/L';
if (newProductCode.indexOf('/') > 0) {
alert('Once you click OK, the text will disappear!!');
newProductCode = newProductCode.replace('/', '\\/');
$('#' + 'div_product-size-icon-' + newProductCode).addClass('active');
}
div.active {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_product-size-icon-121NM/L" class="disabled">Some text here</div>
#Pugazh probably has the correct way of doing it, but you could just isolate the string in " by searching using an attribute in jQuery. Here's a link to the API documentation. It avoids having to do the replace altogether. It's a hacky way of doing it.
var newProductCode = '121NM/L';
$('[id="div_product-size-icon-'+newProductCode+'"]').addClass('active');

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>

concatenate variable with background style broken in my case

$("#home").append('<div style="background:url("http://example.com/images/'+obj[i]+'.jpg")"');
what's wrong here? I think I'd closed it properly..
You have issues with mis-matching quotes - you need to escape the double quotes in the url properties' value, or remove them. You have also not closed the div tag properly. Try this:
$("#home").append('<div style="background:url(http://example.com/images/' + obj[i] + '.jpg)"></div>');
Example fiddle
the problem issued with the string you're building:
'<div style="background:url("http://example.com/images/'+obj[i]+'.jpg")"'
let's assume obj[i]==1.
your div will look like this:
<div style="background:url("http://example.com/images/1.jpg")"
notice two important isssues:
the div has no closing ('>' character)
the style attribute is "background:url(" - having same type of quotes prevent the navigator to understand you.
try use:
$("#home").append('<div style="background:url(/'http://example.com/images/'+obj[i]+'.jpg/')">');
good luck!

Categories