object doesn't support property or method 'search' ie11 - javascript

I have a function in my javascript which is working fine in ie8 but not in ie11. Couldn't understand why it's giving me the error. While debugging it says"object doesn't support property or method 'search'" . Please suggest something. The fine named displayDetails.js and has code like this:
function displayTerm(paymentDropDownId) {
var locPaymentTypeId = null
var index = null;
if (null == paymentDropDownId) {
locPaymentTypeId = this.id;
} else {
locPaymentTypeId = paymentDropDownId;
}
if (null != locPaymentTypeId) {
if (locPaymentTypeId.search("1") > 0) {
index = 0;
} else if(locPaymentTypeId.search("2") > 0) {
index = 1;
} else if(locPaymentTypeId.search("3") > 0) {
index = 2;
}
}
}
Calling it like-
displayTerm(paymentDropDownId);
And
locPaymentOptions.onchange = displayTerm();

Related

How to register/unregister events in a dynamic way, using Vanilla JS

I've spoken to my teacher and he told me that the reason why you would place the <script> element as last part of <body>, use onload= event directly on HTML-element, or in another way include the script in <body> (or deferring its execution), is because you want to guarantee that the script will only be activated once the DOM has been loaded, and the needed elements can be accessed. But... this is not the convention since it will be very difficult to scale in a solution where multiple HTML-documents are involved, sharing the same file resources such as JavaScript in this case. Instead, you'll handle this flow of execution by registering events properly using JS.
I've been told to put the Window Event load at the end my of JS file.
These are the error I get in booking.html: Uncaught TypeError: Cannot read property 'target' of undefined at addEvent (main.js:65) at start (main.js:10) addEvent.
Why do I get this error?
Here is my code:
function start() {
let path = window.location.pathname;
if (path.endsWith("contact.html")) {
browserDetection;
} else if (path.endsWith("employees.html") || path.endsWith("ourfleet.html")) {
registerGalleryEvents();
} else if (path.endsWith("booking.html")) {
addEvent();
getSeat();
}
/* browser detector */
var browserDetection = (function (agent) {
switch (true) {
case agent.indexOf("edge") > -1:
return "MS Edge (EdgeHtml)";
case agent.indexOf("edg") > -1:
return "Microsoft Edge";
case agent.indexOf("opr") > -1 && !!window.opr:
return "Opera";
case agent.indexOf("chrome") > -1 && !!window.chrome:
return "Chrome";
case agent.indexOf("trident") > -1:
return "Internet Explorer";
case agent.indexOf("firefox") > -1:
return "Mozilla Firefox";
case agent.indexOf("safari") > -1:
return "Safari";
default:
return "other";
}
})(window.navigator.userAgent.toLowerCase());
document.getElementById("specific-h3").innerHTML = "Here you can contact us if you have any questions. <br>\ <br>\ And by the way, you are using " + browserDetection + " browser.";
function registerGalleryEvents() {
const galleryImgs = document.querySelectorAll(".galleryImg");
galleryImgs.forEach((galleryImg) => {
galleryImg.addEventListener("click", () => {
displayImage(galleryImg);
});
});
}
//declaring the displayImage function. reference: https://stackoverflow.com/a/65974064/14502646
function displayImage(thumbnail) {
const currentImgSrc = thumbnail.getAttribute("src");
const [imgName, ext] = currentImgSrc.split(".");
document.getElementById('myPicture').src = imgName + '-big.' + ext;
}
var seats = document.getElementsByClassName('grid-item')
// Saving Javascript objects in sessionsStorage.
var data = JSON.parse(sessionStorage.getItem('bookingData'))
function addEvent(event) {
//Makes sure that the first 6 seats are Business class and the rest are Economy.
if (parseInt(event.target.innerHTML) >= 1 && parseInt(event.target.innerHTML) <= 6) {
document.getElementById('classType').innerHTML = 'Class Type: Business'
} else {
document.getElementById('classType').innerHTML = 'Class Type: Economy'
}
//event.target.innerHTML is the number of seat that is selected.
document.getElementById('seat').innerHTML = 'Seat Selected: ' + event.target.innerHTML
document.getElementById('seatNumber').value = event.target.innerHTML
var selectedSeats = document.getElementsByClassName("selected");
if (selectedSeats.length > 0) {
for (var j = 0; j < selectedSeats.length; j++) {
selectedSeats.item(j).className = selectedSeats.item(j).className.replace('grid-item selected', 'grid-item');
}
}
event.target.className = event.target.className + " selected";
}
for (var i = 0; i < seats.length; i++) {
seats[i].addEventListener('click', addEvent)
}
var seatList = document.getElementsByClassName("grid-item")
for (var i = 0; i < data.length; i++) {
seatList.item(parseInt(data[i].seatNo) - 1).removeEventListener("click", addEvent)
seatList.item(parseInt(data[i].seatNo) - 1).className = seatList.item(parseInt(data[i].seatNo) - 1).className.replace('grid-item', 'grid-item booked')
}
document.getElementsByClassName('reset').addEventListener('click', function () {
location.reload()
})
function getSeat() {
var inp = document.getElementsByClassName("grid-item selected");
if (inp.length > 0) {
var inputData = {
firstName: document.getElementById('fname').value,
lastName: document.getElementById('lname').value,
identityNo: document.getElementById('identity').value,
classType: document.getElementById('classType').innerHTML,
seatNo: parseInt(document.getElementById('seatNumber').value)
}
if (JSON.parse(sessionStorage.getItem('bookingData')) != null) {
var bookingData = JSON.parse(sessionStorage.getItem('bookingData'))
bookingData.push(inputData)
sessionStorage.setItem('bookingData', JSON.stringify(bookingData))
} else {
console.log('block')
var bookingData = []
bookingData.push(inputData)
sessionStorage.setItem('bookingData', JSON.stringify(bookingData))
}
alert('Flight booked successfully.')
window.print()
} else {
alert("Select a seat before proceeding!")
}
}
}
window.addEventListener("load", start);

isMatch() function not working correctly in JavaScript

I am trying to use an empty array which fills when clicking on an image send the Image ID to a findMatch() function which in turn is used to insert the a match in a isMatch() function. My isMatch() function is not working correctly. I have tried debugging in Chrome but this is not helping. Any help or advice would be appreciated. I need to clear the array after 2 images are selected.
function isMatch() {
if ((count === 1) && (pic == 1)) {
cMatch.unshift(arrMatch);
match1 = imgID;
}
if ((count === 2) && (pic == 1)) {
// var index2=deClick(clicked);
cMatch.push(arrMatch);
match2 = imgID; {
if (cMatch[0] === cMatch[1]) {
bMatch = true;
cMatch.length = 0;
cMatch = [];
count = 0;
match1 = 0;
match2 = 0;
} else {
bMatch = false;
document.getElementById(match1).src = defaultImage;
document.getElementById(match2).src = defaultImage;
cMatch.length = 0;
cMatch = [];
count = 0;
match1 = 0;
match2 = 0;
}
//else{bMatch=false;}}
}
if (count > 2) {
document.getElementById(match1).src = defaultImage;
document.getElementById(match2).src = defaultImage;
count = 0;
return bMatch;
}
}
}
The code when stepping in Chrome seems to work but when I use in the browser it does not work at all.

Minification leads to redeclaration error in FF and IE

We encountered a problem with the minification provided by the NuGet package Microsoft.AspNet.Web.Optimization, as it seems to have problems with let. Somehow the minifier sets the name of the variables bookingDefaultIndex and i to the same name (i). This makes Firefox and IE 11 report a scope problem (Firefox reports SyntaxError: redeclaration of let i, IE 11 reports Let/Const redeclaration), because the variable was already defined. Without minification, the code works just fine in IE and FF. Chrome reports no problems with the minified code.
In the following code snippets, I marked the relevant lines with a comment that starts with // [SO-COMMENT], so you can search for that to see the problematic lines.
This is the unminified function that causes problems:
_handleDDLValuesByContext: function () {
if (this.options.isCreate) {
if (this.options.isChildCreation) {
//If we are creating a child ->
this.$ddlBookingType.val(this.options.data.BookingTypeID);
this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID);
this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID);
if (this.options.data.ServiceCategoryID == null) {
this.$ddlServiceCategory.val('-1').trigger('change');
if (this.options.data.PricePerUnit != null) {
this.$structureRate.val(GetFormat(this.options.data.PricePerUnit));
}
} else {
this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger('change');
}
//If we are creating a child, prefill his accounting type with the parent accounting type
if (this.options.data.AccountingTypeID == null) {
this.$ddlAccountingType.val('-1').trigger('change');
} else {
this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger('change');
}
} else {
//If it's parent creation ->
let bookingTypes = this.options.structureSpecificData.BookingTypes;
let bookingDefaultID = null;
// [SO-COMMENT] the following variable is minified to 'i'
let bookingDefaultIndex = null;
for (let i = 0, len = bookingTypes.length; i < len; i++) {
if (bookingTypes[i].IsDefault) {
bookingDefaultID = bookingTypes[i].ID;
bookingDefaultIndex = i;
}
}
let allocationTypes = this.options.structureSpecificData.AllocationUnitTypes;
if (bookingDefaultID == null) {
//In case there's no default booking type id, we set the booking types, allocations and effort allocations to their first available value
this.$ddlBookingType.val(bookingTypes[0].ID);
this.$ddlAllocationUnit.val(allocationTypes[0].ID);
this.$ddlEffortAllocationUnit.val(allocationTypes[0].ID);
} else {
let allocationDefaultID = null;
this.$ddlBookingType.val(bookingDefaultID).trigger('change');
allocationTypes = [];
let bookings = this.options.structureSpecificData.BookingTypes;
let allocations = this.options.structureSpecificData.AllocationUnitTypes;
// [SO-COMMENT] this is the 'original' i
for (let i = 0, len = allocations.length; i < len; i++) {
if (allocations[i].BaseUnitID == bookings[bookingDefaultIndex].BaseUnitID) {
allocationTypes.push(allocations[i]);
}
}
for (let i = 0, len = allocationTypes.length; i < len; i++) {
if (allocationTypes[i].IsDefault) {
allocationDefaultID = allocationTypes[i].ID;
}
}
if (allocationDefaultID == null) {
this.$ddlAllocationUnit.val(allocationTypes[0].ID);
this.$ddlEffortAllocationUnit.val(allocationTypes[0].ID);
} else {
this.$ddlAllocationUnit.val(allocationDefaultID);
this.$ddlEffortAllocationUnit.val(allocationDefaultID);
}
}
this.$ddlServiceCategory.val('-1');
}
} else {
//If we are edditing ->
this.$ddlBookingType.val(this.options.data.BookingTypeID);
this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID);
this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID);
if (this.options.data.IsParentElement) {
this.$ddlServiceCategory.val('-1').trigger('change');
//We have to check against a NaN type since the effort and the total cost can be of that type
//in case we have a structure hierarchy with an accounting type of fixed price and therefore no effort and cost
if (isNaN(this.options.structureTotalCost)) {
this.$structureTotalCost.val('');
} else {
this.$structureTotalCost.val(GetFormat(this.options.structureTotalCost));
}
if (isNaN(this.options.structureEffort)) {
this.$structureEffortUnits.val('');
} else {
this.$structureEffortUnits.val(GetFormat(this.options.structureEffort));
}
} else {
if (this.options.data.ServiceCategoryID == null) {
this.$ddlServiceCategory.val('-1').trigger('change');
if (this.options.data.PricePerUnit != null) {
this.$structureRate.val(GetFormat(this.options.data.PricePerUnit));
this._checkTotalCostCalculation();
}
} else {
if (this.options.data.PricePerUnit !== null) {
this.$structureRate.val(GetFormat(this.options.data.PricePerUnit));
this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID);
this._checkTotalCostCalculation();
} else {
this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger('change');
}
}
}
//Since we are editing we should prefill the accounting type with the accounting id and the fixed price too if it exists
//And not trigger anything
if (this.options.data.AccountingTypeID == null) {
this.$ddlAccountingType.val('-1').trigger('change');
} else {
this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger('change');
}
if (isNaN(this.options.totalFixedPrice)) {
this.$fixedPrice.val('');
} else {
this.$fixedPrice.val(GetFormat(this.options.totalFixedPrice));
}
}
}
And this is the minified version:
_handleDDLValuesByContext: function() {
if (this.options.isCreate)
if (this.options.isChildCreation) this.$ddlBookingType.val(this.options.data.BookingTypeID), this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID), this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID), this.options.data.ServiceCategoryID == null ? (this.$ddlServiceCategory.val("-1").trigger("change"), this.options.data.PricePerUnit != null && this.$structureRate.val(GetFormat(this.options.data.PricePerUnit))) : this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger("change"), this.options.data.AccountingTypeID == null ? this.$ddlAccountingType.val("-1").trigger("change") : this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger("change");
else {
let t = this.options.structureSpecificData.BookingTypes,
i = null, // [SO-COMMENT] this shouldn't be named i
r = null;
for (let n = 0, u = t.length; n < u; n++) t[n].IsDefault && (i = t[n].ID, r = n);
let n = this.options.structureSpecificData.AllocationUnitTypes;
if (i == null) this.$ddlBookingType.val(t[0].ID), this.$ddlAllocationUnit.val(n[0].ID), this.$ddlEffortAllocationUnit.val(n[0].ID);
else {
let t = null;
this.$ddlBookingType.val(i).trigger("change");
n = [];
let f = this.options.structureSpecificData.BookingTypes,
u = this.options.structureSpecificData.AllocationUnitTypes;
for (let t = 0, i = u.length; t < i; t++) u[t].BaseUnitID == f[r].BaseUnitID && n.push(u[t]);
// [SO-COMMENT] here there is a second i that causes the problem
for (let i = 0, r = n.length; i < r; i++) n[i].IsDefault && (t = n[i].ID);
t == null ? (this.$ddlAllocationUnit.val(n[0].ID), this.$ddlEffortAllocationUnit.val(n[0].ID)) : (this.$ddlAllocationUnit.val(t), this.$ddlEffortAllocationUnit.val(t))
}
this.$ddlServiceCategory.val("-1")
} else this.$ddlBookingType.val(this.options.data.BookingTypeID), this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID), this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID), this.options.data.IsParentElement ? (this.$ddlServiceCategory.val("-1").trigger("change"), isNaN(this.options.structureTotalCost) ? this.$structureTotalCost.val("") : this.$structureTotalCost.val(GetFormat(this.options.structureTotalCost)), isNaN(this.options.structureEffort) ? this.$structureEffortUnits.val("") : this.$structureEffortUnits.val(GetFormat(this.options.structureEffort))) : this.options.data.ServiceCategoryID == null ? (this.$ddlServiceCategory.val("-1").trigger("change"), this.options.data.PricePerUnit != null && (this.$structureRate.val(GetFormat(this.options.data.PricePerUnit)), this._checkTotalCostCalculation())) : this.options.data.PricePerUnit !== null ? (this.$structureRate.val(GetFormat(this.options.data.PricePerUnit)), this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID), this._checkTotalCostCalculation()) : this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger("change"), this.options.data.AccountingTypeID == null ? this.$ddlAccountingType.val("-1").trigger("change") : this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger("change"), isNaN(this.options.totalFixedPrice) ? this.$fixedPrice.val("") : this.$fixedPrice.val(GetFormat(this.options.totalFixedPrice))
}
My google searches for IIS minification scope problems didn't show any useful results. What could we try to investigate and fix this problem, other than not to use let?

How can I use the arrow keys in Jquery

I'm trying to mimic the Google suggestions list with this:
function el(tid) {
return document.getElementById(tid);
}
function addScript(u) {
var head = document.getElementsByTagName('head')[0],
sc2 = document.createElement('script');
sc2.src = u;
head.appendChild(sc2);
setTimeout(function () {
head.removeChild(sc2);
sc2 = null;
}, 600);
} //end addScript()
function suggest(data) {
var sel = el("test");
sel.innerHTML = '';
for (x = 0; x < data[1].length; x++) {
sel.innerHTML += '<li class="uli" >' + data[1][x][0] + '</li>';
}
}
el("inp").onkeyup = function () {
addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
};
The problem is that I want to be able to come down in the suggestions list using the arrow keys, and secondary I want to show the 'current' suggestion value inside the input field. So I tried something like this using Jquery:
$("#inp").live("keydown", function (e) {
var curr = $('#test').find('.current');
if (e.keyCode == 40) {
if (curr.length) {
$(curr).attr('class', 'uli');
curr = $(curr).next();
}
if (curr.length) {
curr.attr('class', 'uli current');
} else {
$('#center li:first-child').attr('class', 'uli current');
}
}
if (e.keyCode == 38) {
if (curr.length) {
$(curr).attr('class', 'uli');
curr = $(curr).prev();
}
if (curr.length) {
curr.attr('class', 'uli current');
} else {
$('#center li:last-child').attr('class', 'uli current');
}
}
$("#inp").live("keydown", function (e) {
var search_terms = $('li.current').text();
if (e.keyCode == 40) {
$('#inp').val(search_terms);
}
if (e.keyCode == 38) {
$('#inp').val(search_terms);
}
It doesn't work because (I think..) the 'current' suggestion is immediately being requested by the previous code.
I have put everything over here: JS Bin
Why recreate the wheel?
jQuery UI Autocomplete
Or look at other plugins
The problem with your code is you need to cancel out the arrow keypresses when you call to get the values.
el("inp").onkeyup = function () {
//if not the arrow keys, fetch the list
if( ... ){
addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
}
}
Also what is with el("inp") when you are using jQuery? I expected to see $("foo").keyup( function(){} );

Unexpectedly passing integer by reference?

I'm having some issues with this. For some reason, updateCurrentItem is always called with the same parameter regardless.
function updatePromoList(query) {
query = query.toUpperCase();
clearCurrentList();
var numItems = 0;
currentItem = 0;
result_set = cached[query.charAt(0)][query.charAt(1)][query.charAt(2)];
for(i in result_set){
if(numItems >= NUMBER_MATCHES){
$("<li/>").html("<span style='color: #aaa'>Please try to limit your search results</span>").appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(numItems+1); });
break;
}
promo = result_set[i];
found_number = false;
if (!promo.client)
found_number = (promo.prj_number.toString().substr(0,query.length) == query) ? true : false;
if (query.length >= MATCH_NAME) {
if(promo.prj_name && typeof promo.prj_name == 'string'){
found_name = promo.prj_name.toUpperCase().indexOf(query);
} else {
found_name = -1;
}
if (promo.client)
found_client = promo.client_name.toString().indexOf(query);
else
found_client = -1;
} else {
found_name = -1;
found_client = -1;
}
if(found_client >= 0) {
var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.client_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); }); } else if(found_name >= 0 || found_number) { var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.prj_number+": "+promo.prj_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); });
}
if(found_number || found_client >= 0 || found_name >= 0){
numItems++;
}
}
}
function updateCurrentItem(i){
currentItem = i;
console.log("updating to", i);
}
The results of running this are:
setting 0
setting 1
setting 2
setting 3
setting 4
setting 5
setting 6
setting 7
setting 8
setting 9
setting 10
setting 11
setting 12
setting 13
then when I move my mouse over the content area containing these <li>s with the mouseOver events, all I ever see is:
updating to 4
Always 4. Any ideas?
You're creating a closure but it's still bound to the numItems variable:
function(event){ updateCurrentItem(numItems+1); }
What you should do is something like this:
(function(numItems){return function(event){ updateCurrentItem(numItems+1); }})(numItems)
Edit: I think I might have the wrong function but the same principle applies:
function(event){ updateCurrentItem(thisIndex); }
should be
(function(thisIndex)
{
return function(event){ updateCurrentItem(thisIndex); }
})(thisIndex)

Categories