My problem at the moment is that I have a email hyperlink on a page that opens up a new email pop-up screen. Each time the email link is clicked, the To: field in the email pop up will get populated by the email address attached to the hyperlink. If that email has an apostrophe in it, the first time it is clicked it will work ok, but each time after it will change the apostrophe for '%27' (as seen in picture below).
The idea in my script here is to put all of the links in the page into an array, search through that array for the one with the class of "EMAILLINK" and replace the onclick event on that link with a function of my own, which removes the '%27' in the link and puts in an apostrophe.
<script>
// When the page loads
$(document).ready(function () {
// Load all of the link elements into an array
var allLinks = document.getElementsByTagName('a');
// Iterate through all of the links on the page
for (var i=0; i<allLinks.length; i++) {
// When you find one with a class of "EMAILLINK" (an email link)
if (allLinks[i].className=="EMAILLINK") {
// Load the text of the onclick event into a car
var strOldOnclick = allLinks[i].onclick + '';
// Create a regex that matches a single quote, along with part of the function
// used to launch the email pop-up
var testRegex = /(MailTo\(\'.*\%27.*\',event,.*\))/gi;
// Check if the link contains an encoded single quote
if (testRegex.test(strOldOnclick)) {
// Execute the regex against the onclick event
// (loads part of it into variable 1 (RegExp.$1))
testRegex.exec(strOldOnclick);
// Replace the correct onclick text in your string var
var newFunc = "alert('NewFunc running'); if(parent&&parent.frames['EWARE_MENU'])fn=parent;"
+ "else fn=opener.parent;"
+ "if(fn&&fn.frames['EWARE_MENU'])"
+ "fn.frames['EWARE_MENU']."
+ RegExp.$1.replace('%27', "\\'") +";"
// Replace the onclick event for the link with the updated value
$("Before test: " + [allLinks[i]]).attr('onclick','').unbind('click');
$([allLinks[i]]).bind("click", Function(newFunc));
}
}
}
});
</script>
This is the original onclick event on the link when I view the source of the page:
if(parent&&parent.frames['EWARE_MENU'])fn=parent;else fn=opener.parent;if(fn&&fn.frames['EWARE_MENU'])fn.frames['EWARE_MENU'].MailTo('R%27Sakai#demo.com',event,'&Key0=3&Key1=116&Key2=169');
Note: I know the onclick is getting changed correctly as the alert is coming up when I click on the link, so it is something to do with the way I have changed the Javascript in (var newfunc)
A variation of this works in Internet Explorer but not in Chrome (or Firefox) and that is where it is going to be used.
You do not need to write a function of your own, just use the JavaScript unescape() function to remove the apostrophe. If MailTo contains the string with the apostrophe:
var readableString = unescape(MailTo);
Related
I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.
A checkmark might be set by code like this:
if (whatever) checkLocation.innerHTML = CHECKMARK;
Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.
function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);
// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}
// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}
Here's the problem: this works so long as the const CHECKMARK contains something simple, like "X". But specs call for a special HTML character to be used: in this case ✓, or ✓. When I do the comparison (in the if line) it ends up comparing the string "✓" to the string "✓". Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)
Thanks.
There is no problem with the check character and it behaves exactly like the X character. The problem is, that your html have the checkmark character stored as html entity in hex string. If you compare checkmark to checkmark it works just fine: https://jsfiddle.net/m7yoh026/
What you can do in your case is to make sure the CHECKMARK variable is the actuall checkmark character, not the html entity.
Other option is to decode the html entity: https://jsfiddle.net/m7yoh026/3/
var CHECKMARK = '✓'
var decoded_checkmark = $('<textarea />').html(CHECKMARK).text();
console.log($('div')[0].innerHTML)
if ($('div')[0].innerHTML == decoded_checkmark) {
$('body').append('checkmark recognized<br>')
}
You can convert a character to its HTML entity equivalent like so:
var encoded = raw.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:
function encodeHtml(character) {
var element = document.createElement("div");
element.innerHTML = character;
return element.innerHTML;
}
Then I can compare to what it returns, since it automatically changes "✓" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)
Thanks all for the help.
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 'Network Connect'.";
// 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>
So, I have the following script:
<script>
var id = window.location.href
var buttonText = id.substr(id.lastIndexOf('/') + 1);
jQuery("#first_button").html(buttonText)
</script>
So, what it does is that it replaces text of "id=first_button" button with the url next to the last "/".
Here is the set up of URL for my site: mysite.com/first/second/
The problem is that, all my pages end with "/" (ex. .com/something/something/something/).
So, the nothing shows up as there is nothing after the last "/"
Here is what I am trying to achieve essentially.
I have two buttons: First button and Second Button.
And the URl of any pages will follow the same format: `.com/first/second/.
I am trying to replace the first button with /first/ URL and second button with /second/ URL as shown below.
In summary, the code that I have right now only changes the first button text by the URL after the last "/".
I want the URL between first and second "/" (such as ".com/first/") to replace the first button title.
I want the URL between the second and third "/" (such as".com/first/second/") to replace the second button.
In jQuery, how can I target the specific URL section?
Thanks bunch!
You seem to want this :
var parts = window.location.href.split('/').filter(Boolean);
jQuery("#second_button").html(parts.pop());
jQuery("#first_button").html(parts.pop());
split('/') makes an array from the href, pop() takes the last element of that array.
You can also do it with a regular expression:
var m = window.location.href.match(/([^\/]+)\/([^\/]+)\/?$/);
if (m) {
jQuery("#first_button").html(m[1]);
jQuery("#second_button").html(m[2]);
}
If you don't want the two last parts of the href but the two first parts of the path, do it like this:
var m = window.location.pathname.match(/([^\/]+)\/([^\/]+)/);
if (m) {
jQuery("#first_button").html(m[1]);
jQuery("#second_button").html(m[2]);
}
I would like to automate a click in a javascript file used to convert xlsx to csv.
I will provide a snippet of the script that gives the alert. After the alert is given, is there any way to click yes to what is being asked automatically? I am using this to create a formatting utility.
// Determine whether or not linefeed characters should be removed.
var msg = "Would you like to remove linefeed characters from all cells?";
var title = "Remove Linefeed Characters";
var removeLf = alert.Yes == alert(msg, title, alert.YesNo + alert.Question);
// Click 'Yes' button here.
If you always need the user click on YES... ¿why you don't just assign true to alert.Yes?
The below code is part of a javascript function that I am using to highlight keywords:
for (var i = 0; i < keywords.length; i++)
{
var a = new RegExp(keywords[i], "igm");
container.innerHTML = container.innerHTML.replace(a, "<span style='background:#FF0;'>" + keywords[i] + "</span>");
}
It does in fact highlight the words in my search results while allowing the user to click a result. The problem comes when the user clicks a result and is transferred to the page containing more details. Smack in the middle of the URL variables is the 'span' tag.
details.aspx?id=2<span style='background:#FF0> /<span>&name=..
This in turn prevents my details page from being properly populated. If I comment out the problem line and use the below code the variables pass smoothly, but the keywords aren't highlighted:
container.innerHTML = container.innerHTML.replace(a keywords[i] );
My question is how do I remove the span tag from my URL so that my Variables are passed smoothly and the keywords remain highlighted?
because you are doing a text search on a string and your code is matching on the attributes inside of tags. You can not do a simple find and replace and you should not use regular expressions to match tags.