If else does not works properly - javascript

I have a Function (with help of other user of stackoverflow), but only the first if statement works, the second not. I want to take advantage of this code to get both: http and https followed or not by www
function formatURL() {
var url = document.getElementsByName("URL")[0];
var formattedURL = document.getElementsByName("formattedURL")[0];
url = url.value;
if (url.substr(0, 0) === "") // with our without www
{
formattedURL.value = "https://" + url;
return;
} else
{
formattedURL.value = "http://" + url;
return;
}
}
formattedURL.value = url;
}

You're running into this issue because url.substr(0,0) will always be an empty string "" for any string value of url (your if statement is always true).
Not sure what exactly you're trying to compare url.substr against because we don't have all the possible inputs you give to your <URL/> elements. Otherwise, I could have an actual fix for you.

Related

pdf.js downloading as document.pdf instead of filename

I am using pdf.js library in my application.
It has integrated really well except for when i am trying to download the document. Everytime i download a specific file it gets downloaded as document.pdf
I have quite a lot of files to download and this is creating a bit of confusion.
My code goes as below:
<iframe src="pdf_viewer/web/viewer.html?file=/docs/resumes/1b763820-e262-4f76-8502-8872a3cb52e8&filename=sample.pdf"></iframe>
my first parameter is the file id and the second parameter is the name with which the document should be downloaded as.
Below code is the one present in the pdf viewer viewer.js file
function getPDFFileNameFromURL(url) {
var defaultFilename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'document.pdf';
console.log(url);
console.log(defaultFilename);
if (isDataSchema(url)) {
console.warn('getPDFFileNameFromURL: ' + 'ignoring "data:" URL for performance reasons.');
return defaultFilename;
}
var reURI = /^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
try {
suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch (ex) {}
}
}
return suggestedFilename || defaultFilename;
}
From my understanding of the code, what i am doing regarding the input is right. Where could i be going wrong ?
i figured out the solution
<iframe src="pdf_viewer/web/viewer.html?file=/docs/resumes/1b763820-e262-4f76-8502-8872a3cb52e8?sample.pdf"></iframe>
This takes the input in the url, now i can extract filename from the url

How to remove "http://" from domain name inside view

How can I remove "http://" from beginning of a URL inside view in an AngularJS app?
I have URLs in database like:
http://example.com/
http://example.com
example.com
but I only need to show
example.com
inside the view.
This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.
app.filter('domain', function () {
return function (input) {
try {
var url = new URL(input);
return url.hostname;
} catch (DOMException) {
// Malformed URL. Return original (or something else).
return input; }
};
});
URLs that are correct and you might not have thought of:
http://example.com
http://example.com:8000
http://me#example.com
file://example.com
https://example.com
http://example.com/some-path
http://example.com?some-query-url
You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.
use this filter in view
app.filter('domain', function () {
return function (input) {
var output = "",
matches;
var urls = /\w+:\/\/([\w|\.]+)/;
matches = urls.exec( input );
if (matches !== null) output = matches[1];
return output;
};
});

Why does el.style.backgroundImage not work in this functional context?

I wrote an answer for this question: New background according to url, the code I posted in my answer was to check a URL for the presence of a particular string and, if it was there, change the background-image of a given element.
So! Me being me, I thought I'd try and avoid jQuery and go for a more traditional vanilla JavaScript approach with the following:
var images = {
'halloween' : '/images/newbackground.jpg',
'christmas' : '/images/xmasbackground.jpg'
};
var url = document.location.href,
elem = document.getElementById('elementThatYouWantToStyle');
for (var keyword in images){
if (images.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
elem.style.backgroundImage = images[keyword];
}
}
Source.
Which I then thought I'd convert to a functional approach, so it became this:
var images = {
'halloween': 'http://davidrhysthomas.co.uk/img/dexter.png',
'christmas': 'http://davidrhysthomas.co.uk/img/mandark.png'
};
function setBG(el, map, url) {
if (!el || !map) {
return false;
}
else {
var url = url || document.location.href,
el = el.nodeType == 1 ? el : document.getElementById(el);
for (var keyword in map) {
if (map.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
el.style.backgroundImage = encodeURIComponent(map[keyword]);
}
}
}
}
setBG('one', images, 'http://some.domain.com/with/halloween.jpg');
setBG(document.getElementById('two'), images, 'http://some.domain.com/with/christmas.jpg');
JS Fiddle demo.
Now, if I add a console.log() to the if assessment within the for...in loop it shows that we're getting into the loop, and the console suggests that I have an accurate reference to the DOM node, the images object, the URL (as passed into the function) and am getting the correct value from the object.
The following line, however, in which I attempt to set the el.style.backgroundImage property, does not work (this is true whether or not I wrap the map[keyword] in the encodeURIComponent() or not albeit I've linked only to the attempt in which I did. So: what's the obvious flaw in my logic? Why is el.style.backgroundImage not being set?
(Incidentally JS Lint, at JS Fiddle, seems happy with it (other than the redefinition of existing variables (url and el) done in order to have a fall-back/default).
You are declaring a local variable url with var url that already defined as an argument url and you also need to use the form url(http:/xxxx).
Change to this (removed var in front of url and added the url() around the url):
function setBG(el, map, url) {
if (!el || !map) {
return false;
}
else {
url = url || document.location.href;
el = el.nodeType == 1 ? el : document.getElementById(el);
for (var keyword in map) {
if (map.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
el.style.backgroundImage = 'url(' + map[keyword] + ')';
}
}
}
}
An URL is not a valid backgroundImage value unless you wrap it in a url().
el.style.backgroundImage = 'url(' + map[keyword] + ')';
Fiddle
Also, you should not encodeURIcomponent the whole URL, otherwise it will encode even the protocol's : and the /'s, resulting in a 404 as (due to the now lack of protocol) being interpreted as a relative URL:
GET http://fiddle.jshell.net/_display/http%3A%2F%2Fdavidrhysthomas.co.uk%2Fimg%2Fdexter.png 404 (Not Found)
Instead, to more safely encode a full URI you can use encodeURI:
el.style.backgroundImage = 'url("' + encodeURI(map[keyword]) + '")';
Fiddle
Note: MDN mentions that encodeURI may not work as expected in different browsers with GET requests, that is, URLs including query strings. I couldn't reproduce that problem though.
Also as noted by #jfriend00, the var keyword before url is unnecessary, as it already belongs to the function scope due to being declared as a formal parameter. Read more: JavaScript Scoping and Hoisting

How do I access the querystring using javascript?

I have a querystring which looks like this page3.html?redesigndata=value which it appears if its redirected from page1.html and page3.html?new=yes or no when redirected from page2.html. Here is the code I'm using to find out what the querystring is and do some functions on page3.html
var locurl = window.location.search;
if (locurl.substring(0, 13) === '?redesigndata') {
alert("redesign!");
} else if (locurl.substring(0, 4) === '?new') {
visit = locurl.substring(5);
alert("somthing!");
if (visit === 'yes') {
alert("first!");
} else if (visit === 'no') {
alert("again!");
}
}
but I don't get any alerts when I try this script and I cant find out what's wrong with it.
Try using this function
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
Check like this
if(getQueryString()["redesigndata"] != "")
There is nothing wrong with the code you posted. If the alerts never fire, it's because the conditions are never met. Once a query string is added to the URL that DOES match one of those you listed in your code, the alert does fire.
Also, beware you're (seemingly) creating global vars.
The script works on my box. Please put this script inside script tags

Posting data into JavaScript from an URL

I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();

Categories