Changing file path when inserting HTML via JavaScript - javascript

I have a button that runs a batch file, which the code is:
<button onclick="window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat')">Continue</button>
I can put that directly in the HTML file and it works just fine, however I am inserting this specific piece of code into the file via output.innerHTML and it's not working. I assume the "/" have to be changed, but I have also tried:
<button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>...which also does not work. Any ideas what I'm missing here?
JavaScript I am using:
function novpn() {
var output = document.getElementById("main");
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br><button onclick='window.open('file:///C:\\Users\\gthornbu\\Desktop\\TEST\\test.bat')'>Continue</button>";
output.innerHTML = sentence;
}

You have ' nested within '.
The easy way out is to use ", but escaped, as the inner quote. Then go back to the original URL (with forward slashes):
var sentence = "<h3>You are not connected to the VPN. In order to proceed, you must sign in and launch 'Network Connect'.</h3></br>" +
"<button onclick='window.open(\"file:///C:/Users/gthornbu/Desktop/TEST/test.bat\")'>Continue</button>";

You can declare strings with ", ' characters. If you have to call a function with parameter in html attribute, declaration may become a problem.
You can resolve this with escape character. \
It will escape behaving the character caused. You must add before it.
var str = "string";
var str2 = \""string\"";
str === str2 // true
In your case, you can do it like this.
output.innerHTML = '<button onclick="window.open(\'file:///C:/Users/gthornbu/Desktop/TEST/test.bat\')">Continue</button>'
Working JS Fiddle
http://jsfiddle.net/ebilgin/wLe04pwg/

Nesting html markup and javascript code in strings can become an headache to get the single and double quotes right and escaped where needed. Although it allows for some rather rapid application development if you need to maintain this later you might give this solution try.
Instead of figuring out which quote needed to go where I recreated your target html in vanilla javascript commands to create the same result by using different functions and wiring it all together.
I used the document.createElement function to create the html elements needed and the appendChild function to add them to the main element. The button get the function for opening the window attached to the onclick event.
function novpn() {
var output = document.getElementById("main");
// create the h3 elelement and its content
var h3 = document.createElement('h3');
h3.innerHTML = "You are not connected to the VPN. In order to proceed, you must sign in and launch &apos;Network Connect&apos;.";
// the br
var br = document.createElement('br');
// create the button
var button = document.createElement('button');
button.innerHTML = "Continue";
// the onclick handler can now become
// a normal javascript function
button.onclick = function() {
window.open('file:///C:/Users/gthornbu/Desktop/TEST/test.bat');
};
// add all created elements to main
output.appendChild(h3);
output.appendChild(br);
output.appendChild(button);
}
// start
novpn();
<div id='main'>
<div>title</div>
</div>

Related

What is a faster alternative to using document.getElementById('element-id').innerHTML?

I'm making a simple step-by-step wizard for my website which asked viewers questions about their custom order. I've been using JavaScript to replace the content of each "page" with the document.getElementById('element-id').innerHTML command; however, it seems really slow and awkward to add entire divs as a string. For example, some of the code looks something like this:
function loadNextStep() {
document.getElementById('content').innerHTML = 'This is some content.<br>It seems like I need to write everything in one line to make the command work properly.<br><input type="date" id="date-picker" value=""></input>'
}
I'd love to be able to write some multi-line html code, and say "replace everything with this new html."
Is there a faster way of doing the same thing?
Thank you again!
I don't think getElementById or querySelector will make any difference, since the heavier stuff is done when you add a bunch of html elements as a string despite the fact that innerHTML can be vulnerable to cross site scripting if the output of that string has user input commands in it.
But if you still want to do this way you can do by using `` backticks to add as many lines as you'd like.
However, the way I would do is to create those elements on a different function and then output them to your loadNextStep function, then adding to your #content element using the appendChild method.
Here's a quick example of I would do:
function loadNextStep() {
var content = document.getElementById('content');
var step = step1();
step.forEach( stepContent => {
content.appendChild( stepContent );
})
}
function step1() {
var someContent = document.createElement('span');
someContent.innerText = `This is some content. It seems like I need to write everything in one line to make the command work properly.
Yes, but if you use backticks you can have multiple lines.`;
var input = document.createElement('input');
input.type = 'date';
input.id = 'date-picker';
return [ someContent, input ]
}
loadNextStep();
<div id="content">
</div>

Assist with js output and html output stored in var

Hello I am trying to store some html output in a JS var to output it to the page using "getElementById"...
The problem I am having is with single quotes versus double quotes and when to wrap them within each other...
here is my code:
var buttonOutput1="<br/>";
var buttonOutput2="<button onclick="DealCard('player')">Hit</button>";
var buttonOutput5=buttonOutput1+buttonOutput2;
document.getElementById('buttonArea').innerHTML = buttonOutput5;
I know a little about this, I know you can enclose something within single quotes and then enclose that within double quotes and it all works fine.
But because I want to store it all in a variable, I need to enclose it all in a third set of quotes and so therein is my problem.
So just stuck on what I should do here, wondering if anyone can help on this.
Thanks, G
**** My solution 12:51PM EST ****
Was able figure this out by breaking it into pieces:
var buttonOutput1="<br/>";
var buttonOutput2a="DealCard('player')";
var buttonOutput2b='<button onclick="' + buttonOutput2a + '">Hit
Me</button>';
var buttonOutput5=buttonOutput1+buttonOutput2b;
document.getElementById('buttonArea').innerHTML = buttonOutput5;
You can create a DOM node using create Element (DOM Level 2) and attach a function to the onclick attribute.
var domNode = document.createElement('button');
domNode.innerHTML = 'Click me';
domNode.onclick = function() {
alert("hello world")
};
document.getElementById('hook').appendChild(domNode);
<div id="hook"></div>

Jquery switching elements while they are inside a variable

I'm having a little difficulty trying to switch 2 elements around with Jquery when they are inside a string variable.
eg:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
What I would like is to switch the two classes around, making "anotherTest" be infront of "test".
What I've tried so far is:
var myString =
"<div class='chatMessage'>Something here
<div class='test'>My test</div>
<div class='anotherTest'> the other test</div>
Something there
</div>";
var div1 = myString.filter('.test');
var div2 = myString.filter('.anotherTest');
var tdiv1 = div1.clone();
var tdiv2 = div2.clone();
myMessage = div1.replaceWith(tdiv2);
myMessage = div2.replaceWith(tdiv1);
However I receive the following error
t.replace is not a function
I was wondering how I would be able to achieve to switch the two divs around while still stored inside the variable before displaying it to the user?
You're making things harder on yourself by adding the constraint that this needs to be done by direct string manipulation. HTML is meant to be rendered into the DOM -- and since that's a "document object model" it stands to reason it's better-suited for modelling your document as objects.
jQuery may seem a bit old-hat, but its whole purpose is to make querying the DOM easier, so it works well here. All you need to do is parse the string, query the node you want to move, and insert it before the element you want it in front of. You can get the HTML back using $.fn.html(), or you could just leave as an element if you're going to insert it somewhere on your page.
var $el = $(myString);
$('.anotherTest', $el).insertBefore($('.test', $el));
var myMessage = $el.html();
jsfiddle here
Try this one. Just split the string by "</div>", it will make an array of splited contents, then re-add "</div>" to each splited string (this will be consumed in the process of splitting).
Then reassemble.
https://jsfiddle.net/8a4wgn7k/
var myString = "<div class='test'>My test</div><div class='anotherTest'> the other test</div>";
var res = myString.split("</div>");
res[0] +="</div>";
res[1] +="</div>";
var switchedString=res[1]+res[0]

Strange characters in Htmt view

I have a javascript like following
<script type="text/javascript">
var login = "<sec:authentication property="principal.username"/>";
</script>
When i see the value of login is
abc#gmail.com.
What i want that it must be like abc#gmail.com.
Is there is a way I can get the correct lo-gin and not with some weird symbols. Also i would like to know why such weird symbols are occurring instead of proper symbols.
# and . are the HTML codes for # and . respectively.
As far as I know there isin't any native function to decode such string in JavaScript. However you can always use the parsing ability of DOM elements.
var login = (login = document.createElement('span'), login.innerHTML = 'abc#gmail.com', login.textContent);
You can wrap this functionality in a function for reuse:
function decodeHTML(text) {
var el = document.createElement('span');
return el.innerHTML = text, el.textContent;
}
decodeHTML('abc#gmail.com');

how to escape single quote in dynamically created HTML tag content

In my javascript code,
I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";
I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.
content= '<a onclick="javascript:fun(\'' + name + '\');">'
Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help
This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');
// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
fun(name);
return false;
}
anchor.innerHTML = 'hello world';
// later
mydiv.appendChild(anchor);
Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:
The first is to serialize the variable properly; I would use JSON.stringify() for that
The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = '<a href="#" onclick="fun(' +
JSON.serialize(name).replace(/"/g, '"') + ');">hello</a>';

Categories