JavaScript files.length not working in ie9 need alternative approach - javascript

I have the following JavaScript function which is failing in internet explorer 9 on the line which declares the variable filesattached.
function VesselDetails() {
insurancestart = $('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').val();
insuranceend = $('#ctl00_ContentPlaceHolder1_datetimepickerinsend').val();
filesattached = $("input:File")[0].files.length;
//set up JS objects
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').datetimepicker({ format: 'd/m/Y H:i a' });
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').datetimepicker({ format: 'd/m/Y H:i a' });
//subscribe to change events
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').change(function () {
insurancestart = $("ctl00_ContentPlaceHolder1_datetimepickerinsstart").val();
});
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').change(function () {
insuranceend = $("ctl00_ContentPlaceHolder1_datetimepickerinsend").val();
});
$("input:File").change(function () {
filesattached = $("input:File")[0].files.length;
});
ins_client();
}
The ins_client method looks like this:
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
This all works perfectly well in chrome and ie 11 but the length property is returning an undefined for ie 9. I am using the length because I only want the page to be valid for a new vessel request once a document has been submitted, is there another way of doing this which will work in ie 9 onwards and chrome, apologies if this has already been answered elsewhere but I cannot find a workaround anywhere that enables this to continue working in the same way but in ie9 onwards and chrome.

I replaced:
filesattached = $("input:File")[0].files.length;
With:
var areFilesAttached = document.getElementById('ctl00_ContentPlaceHolder1_fuAttachment').value ? true : false;
Within the VesselDetails function.
Then replaced the if statement within ins_client with the following:
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && areFilesAttached == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
This was an alternative approach which enabled me to check whether or not a file had been provided without using the files.length property which is not compatible with IE9.

I'm afraid this can't be achieved, IE9 does not support HTML5 File API and therefore it returns undefined value for files property.
Take a look at FILE API

Related

JavaScript .startWith() function not working in IE, inside angularjs project

Hi im using Angularjs for my project, There is nationality search drop down. I want to map which is typing on Input and filter it inside nationality JSON object. This part is working fine in other browsers except IE. There is console error "Object doesn't support property or method 'startsWith'". this is my code, Can i know how to add "String.prototype.startsWith" for this issue for my code.
$scope.searchNationality = function (data) {
var output = [];
if (data != "" && data != undefined) {
$scope.ShowNationalityDropDown = true;
for (var i = 0; i < $scope.nationalityList.length; i++) {
if ($scope.nationalityList[i].content.toLowerCase().startsWith(data.toLowerCase())) {
output.push($scope.nationalityList[i]);
}
}
$scope.nationalityListSearchResults = output;
} else {
$scope.ShowNationalityDropDown = false;
$scope.nationalityListSearchResults = [];
}
};
You can try changing from .startsWith to .indexOf since it is compatible with IE for lower versions. If .indexOf returns 0 then the string is in the first position of the string that calls that function, which can be usable when you are in this kind of situation that you can't use .startsWith().
const str = "Hey this is a sample string!"
console.log(str.indexOf("Hey") === 0)
console.log(str.indexOf("sample") === 0)
$scope.searchNationality = function (data) {
var thereIsData = data != "" && data != undefined;
var output = thereIsData
? $scope.nationalityList.filter(function (nationality) {
return nationality.content.toLowerCase().indexOf(data.toLowerCase())) == 0;
})
: [];
$scope.ShowNationalityDropDown = thereIsData;
}

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

IE - "Error: Object doesn't support this action"

I'm getting a frustrating javascript error in IE7 that I can't get around. It is working fine in Chrome and Firefox, but not in IE..
The line I am getting the error in is: item = listGetAt(list,'1','-');
This is calling the following custom method:
function listGetAt(list,position,delimiter) {
if(delimiter == null) { delimiter = '-'; }
list = list.split(delimiter);
if(list.length > position) {
return list[position];
} else {
return list.length;
}
}
Can anyone see something I can't?
Many thanks in advance for any help.
Jason
Poor code
Why pass a string as a numeric parameter?
I would consider
function listGetAt(list,position,delimiter) {
delimiter = delimiter || '-';
if (list.indexOf(delimiter) ==-1) return -1;
list = list.split(delimiter);
return list.length>=position?list[position]:null;
}

How to detect if browser supports HTML5 Local Storage

The following code alerts ls exist in IE7:
if(window.localStorage) {
alert('ls exists');
} else {
alert('ls does not exist');
}
IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?
Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.
You don't have to use modernizr, but you can use their method to detect if localStorage is supported
modernizr at github
test for localStorage
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('localstorage', function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
});
updated with current source code
if(typeof Storage !== "undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
This function works fine:
function supports_html5_storage(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
Source: www.diveintohtml5.info
Also I don't want to use Modernizr since I am using only a few HTML5
features and loading a large script isn't worth it just to detect
support for those few things.
To reduce Modernizr file size customize the file at http://modernizr.com/download/ to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.
Try window.localStorage!==undefined:
if(window.localStorage!==undefined){
//Do something
}else{
alert('Your browser is outdated!');
}
You can also use typeof window.localStorage!=="undefined", but the statement above already does it
I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.
If you use jQuery, you can do:
var _supportsLocalStorage = !!window.localStorage
&& $.isFunction(localStorage.getItem)
&& $.isFunction(localStorage.setItem)
&& $.isFunction(localStorage.removeItem);
Or, with pure Vanilla JavaScript:
var _supportsLocalStorage = !!window.localStorage
&& typeof localStorage.getItem === 'function'
&& typeof localStorage.setItem === 'function'
&& typeof localStorage.removeItem === 'function';
Then, you would simply do an IF to test the support:
if (_supportsLocalStorage) {
console.log('ls is supported');
alert('ls is supported');
}
So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.
Try catch will do the job :
try{
localStorage.setItem("name",name.value);
localStorage.setItem("post",post.value);
}
catch(e){
alert(e.message);
}
Try:
if(typeof window.localStorage != 'undefined') {
}
if (window.localStorage){
alert('localStorage is supported');
window.localStorage.setItem("whatever", "string value");
}
Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
function script(){
if(ls){
alert('Yes');
} else {
alert('No');
}
}
<button onclick="script()">Local Storage Support?</button>
I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.
Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.
So without further ado here is my code:
/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */
if (typeof isSessStorageAllowed !== 'function')
{
function isSessStorageAllowed()
{
if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
var ss_test_val = 'ss_test_val_' + String(cur_tm);
sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));
if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
{
return true;
}
else
{
return false;
};
sessionStorage.removeItem(ss_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'session storage' support. [END] */
/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */
if (typeof isLclStorageAllowed !== 'function')
{
function isLclStorageAllowed()
{
if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
var ls_test_val = 'ls_test_val_' + String(cur_tm);
localStorage.setItem(ls_test_itm_key, String(ls_test_val));
if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
{
return true;
}
else
{
return false;
};
localStorage.removeItem(ls_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'local storage' support. [END] */
/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */
/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */
if (typeof isWebStorageAllowed !== 'function')
{
function isWebStorageAllowed()
{
if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
{
return true;
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'web storage' support. [END] */

Browser & version in prototype library?

I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.
In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.
As a completion to nertzy's answer you can add the ability for detecting IE versions using this:
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;
On the other hand you have to detect user agent details on the server side, too.
Anyways browser detection is a seriously flawed strategy for writing cross-browser scripts, that's just to be used when browser feature detection fails. It's pretty easy for a user to alter his/her user agent details.
Prototype offers some flags you can check to get an idea as to which browser is running. Keep in mind that it's much better practice to check for the functionality you wish to use rather than check for a particular browser.
Here is the browser- and feature-detection portion of prototype.js currently in the source tree:
var Prototype = {
Browser: {
IE: !!(window.attachEvent &&
navigator.userAgent.indexOf('Opera') === -1),
Opera: navigator.userAgent.indexOf('Opera') > -1,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
navigator.userAgent.indexOf('KHTML') === -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
SelectorsAPI: !!document.querySelector,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div')['__proto__'] &&
document.createElement('div')['__proto__'] !==
document.createElement('form')['__proto__']
},
}
So you could check if the current browser is IE by investigating the value of Prototype.Browser.IE, or alternatively, be more future-compatible and check for a particular feature like XPath with Prototype.BrowserFeatures.XPath.
You're right - prototype doesn't provide a utility for ascertaining the browser name or version.
If you specifically need to get the browser info as a plugin, I would suggest adding the following (taken from directly jQuery):
var Browser = Class.create({
initialize: function() {
var userAgent = navigator.userAgent.toLowerCase();
this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
this.webkit = /webkit/.test( userAgent );
this.opera = /opera/.test( userAgent );
this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
}
});
I use this over and above Prototype's browser definitions.
Object.extend(Prototype.Browser, {
ie6: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,
ie7: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,
ie8: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,
ie9: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false
});
Hope it helps!
I have prototype.js extended after:
var Prototype = { ... };
with this:
// extension
if (Prototype.Browser.IE) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);
}
}
Works fine for me, calling is like:
if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] == 8) { ... }
<script type="text/JavaScript">
function getBrowserVersion()
{
var msg = "Not Recognised Browser";
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{
var ffversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ffversion == i)
{
msg = "FF" + i + "x";
break;
}
}
}
else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
var ieversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ieversion == i)
{
msg = "IE" + i + "x";
break;
}
}
}
alert(msg); // return msg;
}
</script>

Categories

Resources