javascript example add remove element - javascript

I am struggling with javascript these days, I want to create dynamic add/remove element using java script and i came across following site, but following example doesn't working for me do you know what is wrong in example?
Adding and Removing Elements on the Fly Using JavaScript
I am having issue in following line, which i found using chrome developer tool
var html = '<input type="file" name="uploaded_files[]" /> ' +
'Remove';
Here is the screenshot of google chrome developer tool

You need to escape your quotes.
var html = '<input type="file" name="uploaded_files[]" /> ' +
'Remove';

You might need to escape those single quotes.
onclick="javascript:removeElement(\'file-\' + fileId + ''); return false;">Remove</a>';
That is what I would try.
You want the quotes to be there when you add the text.
You will also have a have files that are named like this
file-1
file-2

Did you add addElement('files', 'p', 'file-' + fileId, html);
At the end of addFile()?
We can't do anything for you if we don't have more information about your 'problem'
Be more explicit in your description.

Related

What's the best way to append html tags to existing text?

I want to use the currently selected text in the office document to be replaced by the same selected text but surrounded with html. Effectively adding a hyperlink to the current selection.
I first read the text property of the selection
var objRange = objContext.document.getSelection();
objRange.load('text');
followed by
return objContext.sync().then(function(){
var strSelection = objRange.text;
objRange.insertHtml(
"<a href='" + decodeURIComponent(strHyperlink) + "'>" + strSelection + "</a>",
Word.InsertLocation.replace
);
return objContext.sync().then(function(){
objDialog.close();
});
});
I need a sync to read the text and then another one to write the updated text back into the document after that I close a dialog. But this sometimes causes the html to get written into the document twice. Is there a better way of doing this instead of with double context syncs?
To answer your question, if you need to read the text and then write into a different context, you'll need two syncs.
But you might take a look at the Range.hyperlink property, which is writeable. I don't know if it'll give you a way to avoid two syncs, but is intended for what you seem to be using insertHtml to do.

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.

Replacing apostrophe in string

I'm using phonegap to share an article via WhatsApp.
The code for the button is as follows:
shareArticle += '<li class="rrssb-whatsapp"><a href="javascript: void(1)" onclick="window.plugins.socialsharing.shareViaWhatsApp(\''+$('.article_title').html().replace(/'/g, "&apos;")+'\', null, \'http://www.myaddress.com/showArticle-'+articleId+'\', function() {console.log(\'share ok\')}, function(errormsg){alert(errormsg)});" class="popup" data-action="share/whatsapp/share">';
shareArticle += '<span class="rrssb-icon"><!-- Icon in SVG --></span>';
shareArticle += '</a></li>';
The part that I'm asking about is this:
onclick="window.plugins.socialsharing.shareViaWhatsApp(\''+$('.article_title').html().replace(/'/g, "&apos;")+'\', null, \'http://www.myaddress.com/showArticle-'+articleId+'\', function() {console.log(\'share ok\')}, function(errormsg){alert(errormsg)});"
The button is not working when there is an apostrophe in the title.
The strangest thing is that if I replace &apos; with " it work perfectly (even thought the result is wrong).
Doe's anybody has any idead why &apos; fails?
Thank you all for your support.
The solution is to change the apostrophe to another sign that doesn't break the string.
So what I did is:
$('.opinion_content_title').html().replace(/'/g, "′")
Again, thank you all.
The named character reference &apos; (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use ' instead of &apos; to work as expected in HTML 4 user agents.

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

How to execute <script> code in a javascript append

I'm working with a plugin that is only Javascript. I need to have it dynamically create a DIV element with an advertisement in it.
I can't figure out why this doesn't work:
$(this).append('<div class="overlay-background">Advertisement
<script type="text-javascript">
GA_googleFillSlot("blog_landing_right_rectangle_300x250");
</script>'
It results in the element created with "Hello World" but it does not execute the GA-googleFillSlot function.
appending HTML into the DOM does not cause the browser to evaluate any script tags in said appended HTML.
If you really wanted to, you could evaluate the javascript by using eval():
eval($(this).find("script").text());
I know this is an old question but I've had a similar problem today.
The solution was using createContextualFragment.
My code looks something like this:
var tagString = '<script async type="text/javascript" src="path_to_script"></script>';
var range = document.createRange();
range.selectNode(document.getElementsByTagName("BODY")[0]);
var documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);
This code works in my browser.
$('body').append('<script>alert("test");<' + '/' + 'script>');
so it might be that $(this) is what is actually causing your problem.
Can you replace it with 'body' and see if it works like that?
One workaround in your case could be to append a fake image with an onload event:
<img src="blank.gif" onload="GA_googleFillSlot('blog_landing_right_rectangle_300x250')" />
since your are in javascript, you can append and then execute the code:
$(this).append('<div class="overlay-background">Advertisement</div>');
GA_googleFillSlot("blog_landing_right_rectangle_300x250");
Please try:
s = '<' + 'script type="text-javascript">' +
'GA_googleFillSlot("blog_landing_right_rectangle_300x250");' +
'<' + '/' + 'script>';
$(this).append(s);
UPD: alas, this won't work, please use wless1's solution instead

Categories