Other js function is ignoring my realtime calc function - javascript

I am at a lost here and have tried everything. My realtime calculation was being done into separate js file, but since I started using bootstrap template, it is not being executed. I have read through it and tried different thing but nothing is happening.
Php for calling realtime calc
<!-- ======================== PHONE INSURANCE ======================== -->
<select name="insurance" id='insurance' onChange="portInDatabase();">
<option disabled >Select Insurance</option>
<option value="None">None</option>
<option value="7">Yes</option>
</select><br>
<!-- ======================== PHONE CASE ======================== -->
<select name="case" id='case' onChange="portInDatabase()" onclick='portInDatabase()'>
<option disabled >Select Phone Case</option>
<option value="None">None</option>
<option value="25">Regular</option>
<option value="30">Wallet</option>
</select><br>
<!-- ======================== SCREEN PROTECTOR ======================== -->
<select name="screen" id='screen' onChange="portInDatabase();">
<option disabled >Select Screen Protector</option>
<option value="None">No</option>
<option value="15">Yes</option>
</select><br>
<!-- ======================== TOTAL FROM JS ======================== -->
<div id='total'></div>
Js for Real time calc(sorry for the long code)
// Array for plan prices
var plan_prices = new Array();
plan_prices["None"]= 0;
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
// Array for insurance where "None" is the id from the html and it is equivalent
// to value 0 and so on
var insurance_phone = new Array();
insurance_phone["None"]=0;
insurance_phone["7"]=7;
//Array for phone case for price calculation
var phone_case = new Array();
phone_case["None"]=0;
phone_case["25"] = 25;
phone_case["30"] = 30;
//Array for screen protector
var screen_protector = new Array();
screen_protector["None"]=0;
screen_protector["15"] = 15;
// function for getting the plan price from the dropList
function getPlanPrice() {
var planSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice3=selectForm.elements["plan"];
planSelected = plan_prices[selectedDevice3.value];
return planSelected;
}// end getPlanPrice
// function for getting the price when it is selected in the html dropList. This
// selection will single out the price we need for calculation.
function getInsurancePrice() {
var insuranceSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice4=selectForm.elements["insurance"];
insuranceSelected = insurance_phone[selectedDevice4.value];
return insuranceSelected;
}// end getInsurancePrice
// Get the price for the selected option in the dropList to calculate.
function getCasePrice() {
var caseSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice5=selectForm.elements["case"];
caseSelected = phone_case[selectedDevice5.value];
return caseSelected;
}// getCasePrice
// function to get the price for the screen.
function getScreenPrice() {
var screenSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice6=selectForm.elements["screen"];
screenSelected = screen_protector[selectedDevice6.value];
return screenSelected;
}// getScreenPrice
// This function splits the data in the database to calculate the price for the
// device when port in is selected or when upgrade is selected and then it also checks
// whether anything else is selected in the form and does the real time calculation and
// outputs the result.
function portInDatabase(){
console.log("PortInDatabase started..")
debugger;
var price1, price2, price3, price4, price5, price6 = 0;
var port = 0;
var newAct = 0;
var up = 0;
var down = 0;
var act= 25; //Activation fee
// if the selection is a number then execute this
if(!isNaN(getPlanPrice())){
price2= getPlanPrice();
}
if(!isNaN(getInsurancePrice())){
price3= getInsurancePrice();
}
if(!isNaN(getCasePrice())){
price4= getCasePrice();
}
if(!isNaN(getScreenPrice())){
price5= getScreenPrice();
}
// This if statement is executed when Port is selected in the dropList and then
// it splits the rows which is connected to the device accordingly and then checks
// whether any of the other dropLists are selected so it can then calulate them and output it.
debugger;
if (document.getElementById('myport').selected == true){
var selDev = document.getElementById('selectDevice').value;
var port = selDev.split('#')[4]; // number of row in the database
port= parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
port = port.toFixed(2); // rounds the decimal to 2
debugger;
document.getElementById('total').innerHTML= "Your Total: " +port;
}//end if
// for new Activation selection
else if(document.getElementById('srp').selected == true){
var selDev = document.getElementById('selectDevice').value;
var newAct = selDev.split('#')[1];
newAct= parseFloat(newAct) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
newAct = newAct.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +newAct;
}//elseif
//for upgrade selection
else if(document.getElementById('upgrade').selected == true){
var selDev = document.getElementById('selectDevice').value;
var up = selDev.split('#')[2];
up = parseFloat(up) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
up = up.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +up;
}//2nd elseif
//for down selection
else if(document.getElementById('down').selected == true){
var selDev= document.getElementById('selectDevice').value;
var down= selDev.split('#')[6];
down = parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
down = down.toFixed(2);
document.getElementsById('total').innerHTML= "Your Total: " +down;
}//end 3rd elseif
else{
return false;
}//end else
}// end portInDatabase
JS of styling that is preventing real time calc
var CuteSelect = CuteSelect || {};
FIRSTLOAD = true;
SOMETHINGOPEN = false;
CuteSelect.tools = {
canRun: function() {
var myNav = navigator.userAgent.toLowerCase();
var browser = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if(browser) {
return (browser > 8) ? true : false;
} else { return true; }
},
uniqid: function() {
var n= Math.floor(Math.random()*11);
var k = Math.floor(Math.random()* 1000000);
var m = String.fromCharCode(n)+k;
return m;
},
hideEverything: function() {
if(SOMETHINGOPEN) {
SOMETHINGOPEN = false;
targetThis = false;
var cells = document.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
var parent = cells[i].parentNode;
cells[i].style.opacity = '0';
cells[i].style.display = 'none';
}
}
}
},
getStyle: function() {
var css = '';
var stylesheets = document.styleSheets;
var css = '';
for(s = 0; s < stylesheets.length; s++) {
var classes = stylesheets[s].rules || stylesheets[s].cssRules;
for (var x = 0; x < classes.length; x++) {
if(classes[x].selectorText != undefined) {
var selectPosition = classes[x].selectorText.indexOf('select');
var optionPosition = classes[x].selectorText.indexOf('option');
var selectChar = classes[x].selectorText.charAt(selectPosition - 1);
var optionChar = classes[x].selectorText.charAt(optionPosition - 1);
if(selectPosition >= 0 && optionPosition >= 0 && (selectChar == '' || selectChar == '}' || selectChar == ' ') && (optionChar == '' || optionChar == '}' || optionChar == ' ')) {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]').replace(/\bselect\b/g, '[data-cuteselect-item]');
continue;
}
if(selectPosition >= 0) {
var character = classes[x].selectorText.charAt(selectPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\bselect\b/g, '[data-cuteselect-item]');
}
}
if(optionPosition >= 0) {
var character = classes[x].selectorText.charAt(optionPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]');
}
}
}
}
}
return css;
},
createSelect: function(item) {
// Create custom select
var node = document.createElement("div");
if(item.hasAttribute('id')) { // Catch ID
node.setAttribute('id', item.getAttribute('id'));
item.removeAttribute('id');
}
if(item.hasAttribute('class')) { // Catch Class
node.setAttribute('class', item.getAttribute('class'));
item.removeAttribute('class');
}
// Hide select
item.style.display = 'none';
// Get Default value (caption)
var caption = null;
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
caption = cells[0].innerHTML;
if(cells[i].hasAttribute('selected')) {
caption = cells[i].innerHTML;
break;
}
}
// Get select options
var options = '<div data-cuteselect-title>' + caption + '</div><div data-cuteselect-options><div data-cuteselect-options-container>';
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('disabled')) { continue; }
if(cells[i].hasAttribute('class')) { var optionStyle = ' class="' + cells[i].getAttribute('class') + '"'; } else { var optionStyle = ''; }
if(cells[i].hasAttribute('id')) { var optionId = ' id="' + cells[i].getAttribute('id') + '"'; } else { var optionId = ''; }
if(cells[i].hasAttribute('selected')) { options += '<div data-cuteselect-value="' + cells[i].value + '" data-cuteselect-selected="true"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
else { options += '<div data-cuteselect-value="' + cells[i].value + '"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
}
options += '</div></div>';
// New select customization
node.innerHTML = caption;
node.setAttribute('data-cuteselect-item', CuteSelect.tools.uniqid());
node.innerHTML = options; // Display options
item.setAttribute('data-cuteselect-target', node.getAttribute('data-cuteselect-item'));
item.parentNode.insertBefore(node, item.nextSibling);
// Hide all options
CuteSelect.tools.hideEverything();
},
//settings of the options, their position and all
show: function(item) {
if(item.parentNode.hasAttribute('data-cuteselect-item')) { var source = item.parentNode.getAttribute('data-cuteselect-item'); }
else { var source = item.getAttribute('data-cuteselect-item'); }
var cells = document.getElementsByTagName('select');
if(item.hasAttribute('data-cuteselect-title')) {
item = item.parentNode;
var cells = item.getElementsByTagName('div');
}
else { var cells = item.getElementsByTagName('div'); }
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
targetItem = cells[i];
cells[i].style.display = 'block';
setTimeout(function() { targetItem.style.opacity = '1'; }, 10);
cells[i].style.position = 'absolute';
cells[i].style.left = item.offsetLeft + 'px';
cells[i].style.top = (item.offsetTop + item.offsetHeight) + 'px';
}
}
item.focus();
SOMETHINGOPEN = item.getAttribute('data-cuteselect-item');
},
selectOption: function(item) {
var label = item.innerHTML;
var value = item.getAttribute('data-cuteselect-value');
var parent = item.parentNode.parentNode.parentNode;
var target = parent.getAttribute('data-cuteselect-item');
var cells = parent.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-title')) { cells[i].innerHTML = label; }
}
// Real select
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) {
var source = cells[i].getAttribute('data-cuteselect-target');
if(source == target) { cells[i].value = value; }
}
//CuteSelect.tools.hideEverything();
},
writeStyles: function() {
toWrite = '<style type="text/css">' + CuteSelect.tools.getStyle() + ' [data-cuteselect-options] { opacity: 0; display: none; }</style>';
document.write(toWrite);
}
};
CuteSelect.event = {
parse: function() {
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) { CuteSelect.tools.createSelect(cells[i]); }
},
listen: function() {
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) { CuteSelect.tools.hideEverything(); }
};
document.onclick = function(event) {
FIRSTLOAD = false;
if((!event.target.getAttribute('data-cuteselect-item') && !event.target.getAttribute('data-cuteselect-value') && !event.target.hasAttribute('data-cuteselect-title')) || ((event.target.hasAttribute('data-cuteselect-item') || event.target.hasAttribute('data-cuteselect-title')) && SOMETHINGOPEN)) {
CuteSelect.tools.hideEverything();
return;
}
//when selected the option dropdown list closes
var action = event.target;
if(event.target.getAttribute('data-cuteselect-value')) {
CuteSelect.tools.selectOption(action);
CuteSelect.tools.hideEverything();
}
else { CuteSelect.tools.show(action); }
return false;
}
},
manage: function() {
if(CuteSelect.tools.canRun()) { // IE Compatibility
CuteSelect.event.parse();
CuteSelect.event.listen();
CuteSelect.tools.writeStyles();
}
}
};
// document.onload(function() {
CuteSelect.event.manage();
// });
I did not want to post this long question, but I am lost and do not know what to do. Thanks and sorry.

Related

Blogger random post display to prevent no posts infinite loop

How can I get Blogger to display random posts, while preventing an infinite loop when there are no posts to display?
Here is my JavaScript code which I am attempting to use:
<script>
var dt_numposts = 10;
var dt_snippet_length = 100;
var dt_info = 'true';
var dt_comment = 'Comment';
var dt_disable = '';
var dt_current = [];
var dt_total_posts = 0;
var dt_current = new Array(dt_numposts);
function totalposts(json) {
dt_total_posts = json.feed.openSearch$totalResults.$t
}
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts\"><\/script>');
function getvalue() {
for (var i = 0; i < dt_numposts; i++) {
var found = false;
var rndValue = get_random();
for (var j = 0; j < dt_current.length; j++) {
if (dt_current[j] == rndValue) {
found = true;
break
}
};
if (found) {
i--
} else {
dt_current[i] = rndValue
}
}
};
function get_random() {
var ranNum = 1 + Math.round(Math.random() * (dt_total_posts - 1));
return ranNum
};
function random_list(json) {
a = location.href;
y = a.indexOf('?m=0');
for (var i = 0; i < dt_numposts; i++) {
var entry = json.feed.entry[i];
var dt_posttitle = entry.title.$t;
if ('content' in entry) {
var dt_get_snippet = entry.content.$t
} else {
if ('summary' in entry) {
var dt_get_snippet = entry.summary.$t
} else {
var dt_get_snippet = "";
}
};
dt_get_snippet = dt_get_snippet.replace(/<[^>]*>/g, "");
if (dt_get_snippet.length < dt_snippet_length) {
var dt_snippet = dt_get_snippet
} else {
dt_get_snippet = dt_get_snippet.substring(0, dt_snippet_length);
var space = dt_get_snippet.lastIndexOf(" ");
dt_snippet = dt_get_snippet.substring(0, space) + "…";
};
for (var j = 0; j < entry.link.length; j++) {
if ('thr$total' in entry) {
var dt_commentsNum = entry.thr$total.$t + ' ' + dt_comment
} else {
dt_commentsNum = dt_disable
};
if (entry.link[j].rel == 'alternate') {
var dt_posturl = entry.link[j].href;
if (y != -1) {
dt_posturl = dt_posturl + '?m=0'
}
var dt_postdate = entry.published.$t;
if ('media$thumbnail' in entry) {
var dt_thumb = entry.media$thumbnail.url
} else {
dt_thumb = "https://blogspot.com/"
}
}
};
document.write('<img alt="' + dt_posttitle + '" src="' + dt_thumb + '"/>');
document.write('<div>' + dt_posttitle + '</div>');
if (dt_info == 'true') {
document.write('<span>' + dt_postdate.substring(8, 10) + '/' + dt_postdate.substring(5, 7) + '/' + dt_postdate.substring(0, 4) + ' - ' + dt_commentsNum) + '</span>'
}
document.write('<div style="clear:both"></div>')
}
};
getvalue();
for (var i = 0; i < dt_numposts; i++) {
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?alt=json-in-script&start-index=' + dt_current[i] + '&max-results=1&callback=random_list\"><\/script>')
};
</script>
Expected output:
?
Actual output:
?
It looks like your post is mostly code; please add some more details.
It looks like you're trying to populate dt_current with dt_numposts = 10 elements. I modified getvalue() as follows, so that dt_numposts is capped at dt_total_posts, which may be 0. This allows the outer for loop to exit.
function getvalue() {
dt_numposts = (dt_total_posts < dt_numposts) ? dt_total_posts : dt_numposts;
// ...
I couldn't test this, because I don't have an example /feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts JSON resource, but it works for zero posts. Whether is works for dt_numposts > 0, you'll need to test!

element null in Magento

I upgrade magento from 1.8.1 to 1.9.0, and I have a problem with one js file:
TypeError: $(...) is null
$('product_addtocart_form').getElements().each(function(el) {
simple_product_pricing.js (line 1131, col 5)
I think this file is related to the Ayasoftware_SimpleProductPricing, maybe someone can help me to solve this. Before upgrade in 1.8.1 version everything was fine, in 1.9.0 version I have this error.
I will add here the entire js:
/*
Some of these override earlier varien/product.js methods, therefore
varien/product.js must have been included prior to this file.
some of these functions were initially written by Matt Dean ( http://organicinternet.co.uk/ )
*/
Product.Config.prototype.getMatchingSimpleProduct = function(){
var inScopeProductIds = this.getInScopeProductIds();
if ((typeof inScopeProductIds != 'undefined') && (inScopeProductIds.length == 1)) {
return inScopeProductIds[0];
}
return false;
};
/*
Find products which are within consideration based on user's selection of
config options so far
Returns a normal array containing product ids
allowedProducts is a normal numeric array containing product ids.
childProducts is a hash keyed on product id
optionalAllowedProducts lets you pass a set of products to restrict by,
in addition to just using the ones already selected by the user
*/
Product.Config.prototype.getInScopeProductIds = function(optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var allowedProducts = [];
if ((typeof optionalAllowedProducts != 'undefined') && (optionalAllowedProducts.length > 0)) {
allowedProducts = optionalAllowedProducts;
}
for(var s=0, len=this.settings.length-1; s<=len; s++) {
if (this.settings[s].selectedIndex <= 0){
break;
}
var selected = this.settings[s].options[this.settings[s].selectedIndex];
if (s==0 && allowedProducts.length == 0){
allowedProducts = selected.config.allowedProducts;
} else {
allowedProducts = allowedProducts.intersect(selected.config.allowedProducts).uniq();
}
}
//If we can't find any products (because nothing's been selected most likely)
//then just use all product ids.
if ((typeof allowedProducts == 'undefined') || (allowedProducts.length == 0)) {
productIds = Object.keys(childProducts);
} else {
productIds = allowedProducts;
}
return productIds;
};
Product.Config.prototype.getProductIdOfCheapestProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var minPrice = Infinity;
var lowestPricedProdId = false;
//Get lowest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice < minPrice) {
minPrice = thisPrice;
lowestPricedProdId = productIds[x];
}
}
return lowestPricedProdId;
};
Product.Config.prototype.getProductIdOfMostExpensiveProductInScope = function(priceType, optionalAllowedProducts) {
var childProducts = this.config.childProducts;
var productIds = this.getInScopeProductIds(optionalAllowedProducts);
var maxPrice = 0;
var highestPricedProdId = false;
//Get highest price from product ids.
for (var x=0, len=productIds.length; x<len; ++x) {
var thisPrice = Number(childProducts[productIds[x]][priceType]);
if (thisPrice >= maxPrice) {
maxPrice = thisPrice;
highestPricedProdId = productIds[x];
}
}
return highestPricedProdId;
};
Product.OptionsPrice.prototype.updateSpecialPriceDisplay = function(price, finalPrice) {
var prodForm = $('product_addtocart_form');
jQuery('p.msg').hide();
jQuery('div.price-box').show();
var specialPriceBox = prodForm.select('p.special-price');
var oldPricePriceBox = prodForm.select('p.old-price, p.was-old-price');
var magentopriceLabel = prodForm.select('span.price-label');
if (price == finalPrice) {
//specialPriceBox.each(function(x) {x.hide();});
magentopriceLabel.each(function(x) {x.hide();});
oldPricePriceBox.each(function(x) { x.hide();
// x.removeClassName('old-price');
// x.addClassName('was-old-price');
});
jQuery('.product-shop').removeClass('sale-product') ;
}else{
specialPriceBox.each(function(x) {x.show();});
magentopriceLabel.each(function(x) {x.show();});
oldPricePriceBox.each(function(x) { x.show();
x.removeClassName('was-old-price');
x.addClassName('old-price');
});
jQuery('.product-shop').addClass('sale-product') ;
}
};
//This triggers reload of price and other elements that can change
//once all options are selected
Product.Config.prototype.reloadPrice = function() {
var childProductId = this.getMatchingSimpleProduct();
var childProducts = this.config.childProducts;
var usingZoomer = false;
if(this.config.imageZoomer){
usingZoomer = true;
}
if(childProductId){
var price = childProducts[childProductId]["price"];
var finalPrice = childProducts[childProductId]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(true);
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
if(this.config.updateShortDescription) {
this.updateProductShortDescription(childProductId);
}
if(this.config.updateDescription) {
this.updateProductDescription(childProductId);
}
if(this.config.updateProductName) {
this.updateProductName(childProductId);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(childProductId);
}
this.showTierPricingBlock(childProductId, this.config.productId);
if (usingZoomer) {
this.showFullImageDiv(childProductId, this.config.productId);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(childProductId);
}
}
} else {
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice");
var price = childProducts[cheapestPid]["price"];
var finalPrice = childProducts[cheapestPid]["finalPrice"];
optionsPrice.productPrice = finalPrice;
optionsPrice.productOldPrice = price;
optionsPrice.reload();
optionsPrice.reloadPriceLabels(false);
if(this.config.updateProductName) {
this.updateProductName(false);
}
if(this.config.updateShortDescription) {
this.updateProductShortDescription(false);
}
if(this.config.updateDescription) {
this.updateProductDescription(false);
}
if(this.config.customStockDisplay) {
this.updateProductAvailability(false);
}
optionsPrice.updateSpecialPriceDisplay(price, finalPrice);
this.showTierPricingBlock(false);
this.showCustomOptionsBlock(false, false);
if (usingZoomer) {
this.showFullImageDiv(false, false);
} else {
if(this.config.updateproductimage) {
this.updateProductImage(false);
}
}
}
};
Product.Config.prototype.updateProductImage = function(productId) {
var imageUrl = this.config.imageUrl;
if(productId && this.config.childProducts[productId].imageUrl) {
imageUrl = this.config.childProducts[productId].imageUrl;
}
if (!imageUrl) {
return;
}
if($('image')) {
$('image').src = imageUrl;
} else {
$$('#product_addtocart_form p.product-image img').each(function(el) {
var dims = el.getDimensions();
el.src = imageUrl;
el.width = dims.width;
el.height = dims.height;
});
}
};
Product.Config.prototype.updateProductName = function(productId) {
var productName = this.config.productName;
if (productId && this.config.ProductNames[productId].ProductName) {
productName = this.config.ProductNames[productId].ProductName;
}
$$('#product_addtocart_form div.product-name h1').each(function(el) {
el.innerHTML = productName;
});
var productSku = this.config.sku ;
if (productId && this.config.childProducts[productId].sku) {
productSku = this.config.childProducts[productId].sku ;
}
jQuery('.sku span').text(productSku) ;
var productDelivery = this.config.delivery;
if (productId && this.config.childProducts[productId].delivery) {
productDelivery = this.config.childProducts[productId].delivery ;
}
jQuery('.delivery-info').html(productDelivery) ;
var productReturns = this.config.returns;
if (productId && this.config.childProducts[productId].returns) {
productReturns = this.config.childProducts[productId].returns ;
}
jQuery('.returns-info').html(productReturns) ;
var productDownloads = this.config.downloads;
if (productId && this.config.childProducts[productId].downloads) {
productDownloads = this.config.childProducts[productId].downloads;
}
if (productDownloads) jQuery('.downloads-info').html(productDownloads) ;
else jQuery('.downloads-info').html('There are no downloads for this product') ;
var productAttribs = this.config.attributesTable;
if (productId && this.config.childProducts[productId].attributesTable) {
productAttribs = this.config.childProducts[productId].attributesTable ;
}
jQuery('.attribs-info').html(productAttribs) ;
decorateTable('product-attribute-specs-table') ;
if (productId && this.config.childProducts[productId].isNew) {
jQuery('.product-image .new-label').show() ;
} else {
jQuery('.product-image .new-label').hide() ;
}
if (productId && this.config.childProducts[productId].isOnSale) {
jQuery('.product-image .sale-label').show() ;
} else {
jQuery('.product-image .sale-label').hide() ;
}
if (productId) jQuery('input[name="pid"]').val(productId) ;
};
Product.Config.prototype.updateProductAvailability = function(productId) {
var stockInfo = this.config.stockInfo;
var is_in_stock = false;
var stockLabel = '';
if (productId && stockInfo[productId]["stockLabel"]) {
stockLabel = stockInfo[productId]["stockLabel"];
stockQty = stockInfo[productId]["stockQty"];
is_in_stock = stockInfo[productId]["is_in_stock"];
}
$$('#product_addtocart_form p.availability span').each(function(el) {
if(is_in_stock) {
$$('#product_addtocart_form p.availability').each(function(es) {
es.removeClassName('availability out-of-stock');
es.addClassName('availability in-stock');
});
el.innerHTML = /*stockQty + ' ' + */stockLabel;
} else {
$$('#product_addtocart_form p.availability').each(function(ef) {
ef.removeClassName('availability in-stock');
ef.addClassName('availability out-of-stock');
});
el.innerHTML = stockLabel;
}
});
};
Product.Config.prototype.updateProductShortDescription = function(productId) {
var shortDescription = this.config.shortDescription;
if (productId && this.config.shortDescriptions[productId].shortDescription) {
shortDescription = this.config.shortDescriptions[productId].shortDescription;
}
$$('#product_addtocart_form div.short-description div.std').each(function(el) {
el.innerHTML = shortDescription;
});
};
Product.Config.prototype.updateProductDescription = function(productId) {
var description = this.config.description;
if (productId && this.config.Descriptions[productId].Description) {
description = this.config.Descriptions[productId].Description;
}
$$('#product_tabs_description_tabbed_contents div.std').each(function(el) {
el.innerHTML = description;
});
};
Product.Config.prototype.updateProductAttributes = function(productId) {
var productAttributes = this.config.productAttributes;
if (productId && this.config.childProducts[productId].productAttributes) {
productAttributes = this.config.childProducts[productId].productAttributes;
}
//If config product doesn't already have an additional information section,
//it won't be shown for associated product either. It's too hard to work out
//where to place it given that different themes use very different html here
console.log(productAttributes) ;
$$('div.product-collateral div.attribs-info').each(function(el) {
el.innerHTML = productAttributes;
decorateTable('product-attribute-specs-table');
});
};
Product.Config.prototype.showCustomOptionsBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if ($('SCPcustomOptionsDiv')==null) {
return;
}
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 1, to: 0.5 });
if(productId) {
//Uncomment the line below if you want an ajax loader to appear while any custom
//options are being loaded.
//$$('span.scp-please-wait').each(function(el) {el.show()});
//prodForm.getElements().each(function(el) {el.disable()});
new Ajax.Updater('SCPcustomOptionsDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
Effect.Fade('SCPcustomOptionsDiv', { duration: 0.5, from: 0.5, to: 1 });
//prodForm.getElements().each(function(el) {el.enable()});
}
});
} else {
$('SCPcustomOptionsDiv').innerHTML = '';
try{window.opConfig = new Product.Options([]);} catch(e){}
}
};
Product.OptionsPrice.prototype.reloadPriceLabels = function(productPriceIsKnown) {
var priceFromLabel = '';
var prodForm = $('product_addtocart_form');
if (!productPriceIsKnown && typeof spConfig != "undefined") {
priceFromLabel = spConfig.config.priceFromLabel;
}
var priceSpanId = 'configurable-price-from-' + this.productId;
var duplicatePriceSpanId = priceSpanId + this.duplicateIdSuffix;
if($(priceSpanId) && $(priceSpanId).select('span.configurable-price-from-label'))
$(priceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
if ($(duplicatePriceSpanId) && $(duplicatePriceSpanId).select('span.configurable-price-from-label')) {
$(duplicatePriceSpanId).select('span.configurable-price-from-label').each(function(label) {
label.innerHTML = priceFromLabel;
});
}
};
//SCP: Forces the 'next' element to have it's optionLabels reloaded too
Product.Config.prototype.configureElement = function(element) {
this.reloadOptionLabels(element);
if(element.value){
this.state[element.config.id] = element.value;
if(element.nextSetting){
element.nextSetting.disabled = false;
this.fillSelect(element.nextSetting);
this.reloadOptionLabels(element.nextSetting);
this.resetChildren(element.nextSetting);
}
}
else {
this.resetChildren(element);
}
this.reloadPrice();
};
//SCP: Changed logic to use absolute price ranges rather than price differentials
Product.Config.prototype.reloadOptionLabels = function(element){
var selectedPrice;
var childProducts = this.config.childProducts;
var stockInfo = this.config.stockInfo;
//Don't update elements that have a selected option
if(element.options[element.selectedIndex].config){
return;
}
for(var i=0;i<element.options.length;i++){
if(element.options[i].config){
var cheapestPid = this.getProductIdOfCheapestProductInScope("finalPrice", element.options[i].config.allowedProducts);
var mostExpensivePid = this.getProductIdOfMostExpensiveProductInScope("finalPrice", element.options[i].config.allowedProducts);
var cheapestFinalPrice = childProducts[cheapestPid]["finalPrice"];
var mostExpensiveFinalPrice = childProducts[mostExpensivePid]["finalPrice"];
var stock = '';
if(cheapestPid == mostExpensivePid ){
if(stockInfo[cheapestPid]["stockLabel"] != '') {
stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
if (this.config.showOutOfStock){
if(this.config.disable_out_of_stock_option ) {
if(!stockInfo[cheapestPid]["is_in_stock"] ) {
if(cheapestPid == mostExpensivePid ){
element.options[i].disabled=true;
var stock = '( ' +stockInfo[cheapestPid]["stockLabel"] + ' )';
}
}
}
}
var tierpricing = childProducts[mostExpensivePid]["tierpricing"];
element.options[i].text = this.getOptionLabel(element.options[i].config, cheapestFinalPrice, mostExpensiveFinalPrice, stock , tierpricing);
}
}
};
Product.Config.prototype.showTierPricingBlock = function(productId, parentId) {
var coUrl = this.config.ajaxBaseUrl + "co/?id=" + productId + '&pid=' + parentId;
var prodForm = $('product_addtocart_form');
if(productId) {
new Ajax.Updater('sppTierPricingDiv', coUrl, {
method: 'get',
evalScripts: true,
onComplete: function() {
$$('span.scp-please-wait').each(function(el) {el.hide()});
}
});
} else {
$('sppTierPricingDiv').innerHTML = '';
}
};
//SCP: Changed label formatting to show absolute price ranges rather than price differentials
Product.Config.prototype.getOptionLabel = function(option, lowPrice, highPrice, stock, tierpricing){
var str = option.label;
if(tierpricing > 0 && tierpricing < lowPrice) {
var tierpricinglowestprice = ': As low as (' + this.formatPrice(tierpricing,false) + ')';
} else {
var tierpricinglowestprice = '';
}
if (!this.config.showPriceRangesInOptions) {
return str;
}
if (!this.config.showOutOfStock){
stock = '';
}
lowPrices = this.getTaxPrices(lowPrice);
highPrices = this.getTaxPrices(highPrice);
if (this.config.hideprices) {
if (this.config.showOutOfStock){
return str + ' ' + stock + ' ';
} else {
return str;
}
}
var to = ' ' + this.config.rangeToLabel + ' ';
var separator = ': ( ';
if(lowPrice && highPrice){
if (this.config.showfromprice) {
this.config.priceFromLabel = this.config.priceFromLabel; //'From: ';
}
if (lowPrice != highPrice) {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str+= to + this.formatPrice(highPrices[2], false) + ' (' + this.formatPrice(highPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
} else {
str+= separator + this.formatPrice(lowPrices[0], false);
str+= to + this.formatPrice(highPrices[0], false);
str += " ) ";
}
} else {
if (this.taxConfig.showBothPrices) {
str+= separator + this.formatPrice(lowPrices[2], false) + ' (' + this.formatPrice(lowPrices[1], false) + ' ' + this.taxConfig.inclTaxTitle.replace('Tax','VAT') + ')';
str += " ) ";
str += stock;
str += tierpricinglowestprice;
} else {
if(tierpricing == 0 ) {
str+= separator + this.formatPrice(lowPrices[0], false);
str += " ) ";
}
str += tierpricinglowestprice;
str += ' ' + stock;
}
}
}
return str;
};
//SCP: Refactored price calculations into separate function
Product.Config.prototype.getTaxPrices = function(price) {
var price = parseFloat(price);
if (this.taxConfig.includeTax) {
var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
var excl = price - tax;
var incl = excl*(1+(this.taxConfig.currentTax/100));
} else {
var tax = price * (this.taxConfig.currentTax / 100);
var excl = price;
var incl = excl + tax;
}
if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
price = incl;
} else {
price = excl;
}
return [price, incl, excl];
};
//SCP: Forces price labels to be updated on load
//so that first select shows ranges from the start
document.observe("dom:loaded", function() {
//Really only needs to be the first element that has configureElement set on it,
//rather than all.
if (typeof opConfig != "undefined") {
spConfig.reloadPrice();
}
$('product_addtocart_form').getElements().each(function(el) {
if(el.type == 'select-one') {
if(el.options && (el.options.length > 1)) {
el.options[0].selected = true;
spConfig.reloadOptionLabels(el);
}
}
});
});
Thank you
The version 1.5.11 is not compatible w/ Magento 1.9 according to the extension version on Magento connect. Please obtain the newest version of the extension and/or ask the creator to give you support. As far as I can see 1.9 support is support with 1.11.6, released 11th March 2015. The infos on their homepage and Magento connect are different - not good. On the homepage it says Works with Magento 1.9.0.X . tested 15 May 2014.

Can't validate this! Validation process keeps stopping

I'm having problems validating this piece of javascript code. JSlint keeps stopping after the first for instruction and I can't seem to figure out why. It seems as if the validator is picking on warnings rather than errors (such as "use space instead of tabs" or "expected +=1 instead of ++" which all seem fine to me). Also, I'm not sure if it does what it's supposed to but I can't check that until I get the validation done.
var prompt = document.getElementById("prompt");
var response = document.getElementById("response");
var warning = document.getElementById("warning");
var fixation = 'fixPlus.jpg';
var cueImage = ['fixPlus.jpg', 'midCue.jpg', 'bothCue.jpg', 'topCue.jpg', 'botCue.jpg'];
//images for stimuli were taken from wheedesign.com
var stImage = ['T_L_N.jpg', 'T_L_C.jpg', 'T_L_I.jpg', 'T_R_N.jpg', 'T_R_C.jpg', 'T_R_I.jpg', 'B_L_N.jpg', 'B_L_C.jpg', 'B_L_I.jpg', 'B_R_N.jpg', 'B_R_C.jpg', 'B_R_I.jpg'];
var condIdx[1];
var i;
for (i = 2, i <= 47; i++) {
condIdx.push(i);
}
var cueType = ['0', '1', '2']; //I will use a repetitive instruction instead of writing 000,111, etc
for (i = 0; i < 11; i++) {
cuetype[i] = 0;
}
for (i = 12; i < 23; i++) {
cueType[i] = 1;
}
for (i = 24; i < 35; i++) {
cueType[i] = 2;
}
for (i = 36; i < 41; i++) {
cueType[i] = 3;
}
for (i = 42; i < 47; i++) {
cueType[i] = 4;
}
var stType = ['0', '1', '2', '3', '4', '5', '6', '7'];
var ansKey = ['Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'M', 'M', 'M', 'M', 'M', 'M'];
var promptTxt = 'Press Z for left and M for right';
var invalidTxt = ' -- Invalid key press!!!';
var correctTxt = 'correct answer!';
var incorrectTxt = 'incorrect answer!'
var waitTxt = 'Wait for the prompt!';
var tooSlow = 'Too slow!';
var toa = 400; //trial onset asynchrony in ms
var preCueFixTime[500, 600, 700, 800, 900, 1000, 1100, 1200]; //pre-cue fixation
var cueTime = 100; // cue in ms
var postCueTime = 400; //post-cue fixation
var maxStTime = 1500; //stimulus display (until a key is pressed or 1500ms has lapsed)
var promptTime = 1500; // duration of response prompt in ms
var nTrial = isPractice ? 1 : 24;
var trialCounter = 0; //to keep track of progress
var remainStr = ''; //remaining trials
var doneStr = ''; //trials completed
var indxChar = '='; //character used to indicate a trial
var remainColor = 'LightBlue'; //color to display remainStr
var doneColor = 'Navy';
var progTxt = 'Progress: '.fontcolor(doneColor);
var rspArr = []; //to store responses
var cssFile = '<link rel = "stylesheet" type = "text/css" href = "rngStyle.css">';
var blocks = 0;
function block_initiation() {
if (blocks < 7) {
warning.innerHTML = '';
response.innerHTML = '';
object.onclick = "trialBlock()" + 'Click here to begin a block of trials!';
blocks++;
updateProgress();
} else {
submitData();
}
}
function trialBlock() {
"use strict";
condIdx = shuffle(condIdx);
preCueFixTime = shuffle(preCueFixTime);
cueImage = shuffle(cueImage);
for (i = 0; i < 6; i++) {
var theTask = setInterval(function () {
aTrial();
}, toa);
}
}
function aTrial() {
"use strict";
if (trialCounter < nTrial) {
warning.innerHTML = '';
response.innerHTML = '';
getKeypress();
trialCounter++;
updateProgress();
} else {
submitData();
}
}
function getKeypress() {
"use strict";
rspArr.push(0);
// fixation - cue - fixation - stimulus - key press/too slow
var interval = window.setInterval(function () {
if (fixation.display == 'hidden') {
fixation.style.visibility = 'visible';
} else {
fixation.style.visibility = 'hidden';
}
}, preCueFixTime[trialCounter]); //display initial fixation
if (cueImage[trialCounter].display == 'hidden') {
cueImage[trialCounter].style.visibility = 'visible';
} else {
cueImage[trialCounter].style.visibility = 'hidden';
}
}, 100); //shows cue display for 100ms
prompt.innerHTML = promptTxt; //show the prompt text
setTimeout(function () {
prompt.innerHTML = '';
}, promptTime);
if (stImage[condIdx[trialCounter]].display == 'hidden') {
stImage[condIdx[trialCounter].style.visibility = 'visible';
} else {
stImage[condIdx[trialCounter]].style.visibility = 'hidden';
}
}, 1500);
setTimeout(function () {
tooSlow.innerHTML = '';
}, tooSlow);
var inputRecorded = false;
document.onkeydown = function (e) {
if (inputRecorded) {
warning.innerHTML = waitTxt;
cueImage[trialCounter].style.visibility = 'hidden';
return false; //to cancel the event
}
e = e || window.event;
var key_press = String.fromCharCode(e.keyCode);
var regex = /[MZ]/;
condIdx[trialCounter].innerHTML = '';
//stImage[indeces 1 to 6] should be Z and stImage[7-12] should be M
var stStart = new Date();
fixation + cueImage[trialCounter] + fixation + stImage[condIdx[trialCounter]];
setTimeout(function () {
fixation.innerHTML = '';
}, preCueFixTime[trialCounter]); //this will still show preCueFixTime in ascending order
if (key_press.search(regex) > -1) {
var stEnd = new Date();
var RT = stEnd.getTime() - stStart.getTime();
//something was pressed
if (condIdx[trialCount] < 7 && key_press == 'Z'
OR condIdx[trialCount] >= 7 && key_press == 'M') {
//correct!
var correct = true;
trialCond = [cond Idx, cueType, correct, RT];
rspArr[trialCount] = trialCond.join();
response.innerHTML = key_press;
clearInterval(tooSlow); // cancel Too Slow
clearInterval(stImage[trialCounter]); //cancel stimulus display
warning.innerHTML = correctTxt;
} else {
//incorrect!
var correct = false;
rspArr[rspArr.length - 1] = key_press;
response.innerHTML = key_press;
clearInterval(tooSlow); // cancel Too Slow
clearInterval(stImage[trialCounter]); //cancel stimulus display
warning.innerHTML = incorrectTxt;
}
} else {
warning.innerHTML = key_press + invalidTxt;
}
inputRecorded = true;
}; //document.onkeydown
}
function updateProgress() {
"use strict";
//alert (trialCounter + ' ' + remainStr);
if (trialCounter === 0) {
for (var i = 0; i < nTrial; i++) {
remainStr += indxChar;
}
} else {
doneStr += indxChar;
remainStr = remainStr.slice(0, -1);
}
progress.innerHTML = progTxt + doneStr.fontcolor(doneColor) + remainStr.fontcolor(remainColor);
}
function checkProgress() {
"use strict";
var j, tot = 0,
n = rspArr.length;
//alert(tot + ' ' + n);
for (j = n - 5; j < n; j++) {
if (rspArr[j] > 0) {
tot++;
}
}
var actionAttr, fbkTxtm, valueAttr;
if (tot > 3) {
actionAttr = 'action="rng04Task.php"';
fbkTxt = '<h2>Good! That ends the practice. </h2>';
valueAttr = 'value="Click here to formally begin the task"';
} else {
actionAttr = 'action="rng03Practice.php"';
fbkTxt = '<h2>You are not quite in sync with the prompts </h2>' + '<h2> Please try again </h2>';
valueAttr = 'value="Click here to have some more practice"';
}
document.write(cssFile +
'<form class="center"' + actionAttr + '>' + fbkTxt + '<input class = "myButton" type="submit"' + valueAttr + '>' + '</form>');
//alert(cssFile +
//'<form class="center"' + actionAttr + '>' + fbkTxt + '<input class = "myButton" type="submit"' + valueAttr + '>' + '</form>');
}
function shuffle(arr) {
"use strict";
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return arr;
//function taken and adapted from http://jsfromhell.com/array/shuffle
};
function submitData() {
"use strict";
}
I suspect it's failing on:
var condIdx[1];
As I don't think that's valid js syntax. You are attempting to declare a variable name, and provide a size/or access an index, in the same line, without an equality statement?

javascript function for calculating

I meet a trouble with a function. actually I need to make this function to perform a calculation on some text fields. When I worked on a single line no problems. But recently, someone asked to make a table with multiple lines (one line can be added dynamically) so, I do the following function so that it can not only duplicate line but id change all the fields concerned, so I add class to these fields. therefore I proceed as follows:
function clone(line) {
newLine = line.cloneNode(true);
line.parentNode.appendChild(newLine);
var tab = document.getElementsByClassName('libelle_debours')
var i = -1;
while (tab[++i]) {
tab[i].setAttribute("id", "_" + i);
};
var cab = document.getElementsByClassName('ht_no_tva')
var j = -1;
while (cab[++j]) {
cab[j].setAttribute("id", "_" + j);
};
var dab = document.getElementsByClassName('ht_tva')
var k = -1;
while (dab[++k]) {
dab[k].setAttribute("id", "_" + k);
};
var eab = document.getElementsByClassName('taux')
var l = -1;
while (eab[++l]) {
eab[l].setAttribute("id", "_" + l);
};
var fab = document.getElementsByClassName('tva')
var m = -1;
while (fab[++m]) {
fab[m].setAttribute("id", "_" + m);
};
}
function delRow() {
var current = window.event.srcElement;
//here we will delete the line
while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.removeChild(current);
}
The problem in fact is the second function that is used to make the calculation:
function calcdebours() {
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva = Math.round((((ht_tva) * (taux)) / 100) * 100) / 100;;
if (taux == '') {
taux = 0;
}
if (ht_no_tva == '') {
ht_no_tva = 0;
}
if (ht_tva == '') {
ht_tva = 0;
}
document.getElementById('debours_montant_tva').value = tva;
document.getElementById('debours_montant_ttc').value = (tva) + parseFloat(ht_tva) + parseFloat(ht_no_tva)
}
function
montant_debours() {
var ttc = document.getElementById('debours_montant_ttc').value;
var ttc2 = document.getElementById('debours_montant_ttc2').value;
if (ttc == '') {
var ttc = 0;
} else {
var ttc = document.getElementById('debours_montant_ttc').value;
}
if (ttc2 == '') {
var ttc2 = 0;
} else {
var ttc2 = document.getElementById('debours_montant_ttc2').value;
}
tx = parseFloat(ttc) + parseFloat(ttc2);
document.getElementById('ttc_cheque').value = Math.round(tx * 100) / 100;
}
As Id are not the same, do I have to create as many functions
there are lines?
Is it possible to fit a single function to process each line?
If so can you tell me how?
If I'm not mistaken you can use for loop and append increment to the end of element's id. Like this:
trs = document.getElementById('container Id').getElementsByTagName('tr');
For (var i = 1, i <= trs.length; i++)
{
var el = document.getElementById('debours_montant_ttc' + i);
}

Javascript .Replace Alternative

I am coding a template for eBay. However, eBay does not allow .replace. The code below is for a rollover tab section.When the user hovers over tab(a), the correspodning div div(a) is made to become visible.
Is there a workaround to get the code to work without using .replace?
var divs = new Array();
divs.push("contentPayment");
divs.push("contentShipping");
divs.push("contentWarranty");
divs.push("contentContact");
var navs = new Array();
navs.push("nav1");
navs.push("nav2");
navs.push("nav3");
navs.push("nav4");
///////////////////////////////////////
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
///////////////////////////////////////////////////////////////////////
function toggleDisplay(id) {
for (var i = 0; i < divs.length; i++) {
var item = document.getElementById(divs[i]);
item.style.display = 'none';
}
var target = document.getElementById(id);
target.style.display = 'block';
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////PAYMENT IS HOVERED////////////////////////////////////////////////////////
if (id == "contentPayment") {
var CurrentTab = document.getElementById("nav1");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Shipping IS HOVERED////////////////////////////////////////////////////////
if (id == "contentShipping") {
var CurrentTab = document.getElementById("nav2");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Warranty IS HOVERED////////////////////////////////////////////////////////
if (id == "contentWarranty") {
var CurrentTab = document.getElementById("nav3");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Contact IS HOVERED////////////////////////////////////////////////////////
if (id == "contentContact") {
var CurrentTab = document.getElementById("nav4");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
}
You may try this as an alternative of replace function
String.prototype.fakeReplace = function(str, newstr) {
return this.split(str).join(newstr);
};
var str = "Welcome javascript";
str = str.fakeReplace('javascript', '');
alert(str); // Welcome
DEMO.
For a more efficient, but slightly longer method, use this:
String.prototype.myReplace = function(pattern, nw) {
var curidx = 0, len = this.length, patlen = pattern.length, res = "";
while(curidx < len) {
var nwidx = this.indexOf(pattern, curidx);
console.log(nwidx);
if(nwidx == -1) {
break;
}
res = res + this.substr(curidx, nwidx - curidx);
res = res + nw;
curidx = nwidx + patlen;
}
return res;
};
alert("Glee is awesome".myReplace("awesome", "very very very awesome"));
See it in action: little link.
Hope that helped!

Categories

Resources