jQuery noConflict mode - javascript

I'm trying to use jQuery on a Joomla site, and Joomla loads jQuery in noConflict mode. I'm trying to wrap my code in (function($){ ... })(jQuery);.
This works:
function calculate()
{
var de = document.calculator.de.value;
var para = document.calculator.para.value;
var quantia = document.calculator.quantia.value;
var pais = jQuery("#para option:selected").text();
var curr = (pais == "Brazil" ? "Reais" : "Euro");
var tax = (pais == "Brazil" ? 0 : 3)
result = Math.round(quantia * para) + ' ' + curr;
jQuery('#result').text(result);
e.preventDefault();
return false;
}
This doesn't work (Uncaught ReferenceError: calculate is not defined):
(function($){
function calculate()
{
var de = document.calculator.de.value;
var para = document.calculator.para.value;
var quantia = document.calculator.quantia.value;
var pais = $("#para option:selected").text();
var curr = (pais == "Brazil" ? "Reais" : "Euro");
var tax = (pais == "Brazil" ? 0 : 3)
result = Math.round(quantia * para) + ' ' + curr;
$('#result').text(result);
e.preventDefault();
return false;
}
})(jQuery);
I'm probably missing a small detail, but where am I going wrong?

The function calculate is local to the closure. The best solution would be putting all of your code into the closure. In case this is not possible you can assign the function to window via:
window.calculate = calculate;
You can also return it from the closure and then assign it to the calculate variable:
calculate = (function($) {
...
return calculate;
})(jQuery);

Related

Javascript/JS - Referring to classes and variables dynamically within a change event loop

I'm trying to cut down this list of class change functions to one neat loop using an array for the class names used in the change event.
I need to put the four example $ ('.[class]').change functions into a loop. The D7codes array doesn't read in as a dynamic class changer (where I've put [class] in this comment). Also, do I need an overall change function so the loop executes each time?
Currently it works in long hand how I want it to, but I'm going to need to use this autosum throughout a project that other people will need to refer to, and it's going to get really messy.
This code looks for change (check box) in a class - I haven't included the python and html elements because it works correctly currently. There are four functions that need to be in a loop.
Apart from the class names in the D7codes array the only other two things that change within the functions are the numbers, ascending, after the 'question' and 'click' variables (0-4)
var question0 = 15.99;
var question1 = 20.99;
var question2 = 5.99;
var question3 = 2.99;
var total = 0
var click0 = false;
var click1 = false;
var click2 = false;
var click3 = false;
var click99 = false;
//this array is for the class names (currently the array isn't being used as I've elongated the code back out
var D7codes = [d7-r6,d7-r7,d7-r8,d7-r9]
//the four functions that should be in a loop
$ ('.d7-r6').change( function() {
click0 = !click0;
if (!click99) {
total += click0 ? question0 : -question0
} else {
totalOrig += click0 ? question0 : -question0
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
$ ('.d7-r7').change( function() {
click1 = !click1;
if (!click99) {
total += click1 ? question1 : -question1
} else {
totalOrig += click1 ? question1 : -question1
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
$ ('.d7-r8').change( function() {
click2 = !click2;
if (!click99) {
total += click2 ? question2 : -question2
} else {
totalOrig += click2 ? question2 : -question2
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
$ ('.d7-r9').change( function() {
click3 = !click3;
if (!click99) {
total += click3 ? question3 : -question3
} else {
totalOrig += click3 ? question3 : -question3
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
//This next function doesn't need to be in the loop but is referred to so I've //left it in for clarity
$ ('.d7-r99').change( function() {
click99 = !click99;
if (click99) {
totalOrig = total;
total = 0;
} else {
total = totalOrig;
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
Got there in the end:
var total = 0
var click99 = false;
var question = [15.99, 20.99, 5.99, 2.99];
var click = [false, false, false, false];
//classnames
var D7codes = ['.d7-r6','.d7-r7','.d7-r8','.d7-r9']
D7codes.forEach( function( value, index ) {
$ (value).change( function() {
click[index] = !click[index];
if (!click99) {
total += click[index] ? question[index] : -question[index]
} else {
totalOrig += click[index] ? question[index] : -question[index]
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
});
$ ('.d7-r99').change( function() {
click99 = !click99;
if (click99) {
totalOrig = total;
total = 0;
} else {
total = totalOrig;
};
var totalFloat = parseFloat(total).toFixed(2);
$ ('.asum-total').text(totalFloat);
});
Chris G gave a great answer in the comments also (I couldn't use it with the software I'm using but it would work outside of my particular project)

ASP.net MVC bundle minficiation duplicate variable name conflict

I am receiving a JavaScript error due to the ASP.net bundle functionality, the JS code works fine before it gets minified but not after.
The issue Is have a isSelected variable that contains a boolean. But when the code gets minified it shortens this variable name to i. But in the $.each method I create an inline function with two parameters one being i.
It seems the minification logic failed to realize that renaming the variable to i would conflict with the code in my inline function.
Is this a bug with the ASP.net bundling system? If not how am I recommended to solve this, I am concerned that although I could just rename the parameter name that this bug could crop up in other parts of my web application.
Original JS code
function ItemManagerUpdateUi(instance) {
var selectedValue = instance.ItemCombo.GetValue();
var selectedItem = ItemManagerGetSelectedItem(instance);
var isSelected = selectedValue != null;
var isNewSelected = selectedValue == -1;
var applyText = isNewSelected ? "Add" : "Apply";
var text = isNewSelected ? "" : instance.ItemCombo.GetText();
var highestSortOrder = 0;
$.each(instance.Items, function (i, e) {
if (e.SortOrder > highestSortOrder)
highestSortOrder = e.SortOrder;
});
var sortOrder = isNewSelected || !isSelected ? highestSortOrder + 1 : selectedItem.SortOrder;
$('#' + instance.EditPanelId).toggle(isSelected);
$('#' + instance.ApplyButtonId).val(applyText);
$('#' + instance.DeleteButtonId).toggle(!isNewSelected);
var labelWidth = $(instance.ItemCombo.GetMainElement()).closest('.rbox-clearfix').find('.labelStyle').width() + 15;
$('#' + instance.ButtonPanelId).css('margin-left', labelWidth + 'px');
instance.TextControl.SetText(text);
instance.SortOrderControl.SetNumber(sortOrder);
$.each(instance.CustomFields, function (i, e) {
var value = isNewSelected || !isSelected ? null : selectedItem[e.DataName];
var dxControl = eval(e.ControlName);
dxControl.SetValue(value);
dxControl.SetIsValid(true);
});
if (!isNewSelected)
$(instance.ItemCombo.GetMainElement()).find('.dms-combo-main-input').removeClass('newActivityItem');
instance.TextControl.SetIsValid(true);
}
JS code after minification
function ItemManagerUpdateUi(n) {
var u = n.ItemCombo.GetValue(),
f = ItemManagerGetSelectedItem(n),
i = u != null,
t = u == -1,
s = t ? "Add" : "Apply",
h = t ? "" : n.ItemCombo.GetText(),
r = 0,
e,
o;
$.each(n.Items, function(n, t) {
t.SortOrder > r && (r = t.SortOrder)
});
e = t || !i ? r + 1 : f.SortOrder;
$("#" + n.EditPanelId).toggle(i);
$("#" + n.ApplyButtonId).val(s);
$("#" + n.DeleteButtonId).toggle(!t);
o = $(n.ItemCombo.GetMainElement()).closest(".rbox-clearfix").find(".labelStyle").width() + 15;
$("#" + n.ButtonPanelId).css("margin-left", o + "px");
n.TextControl.SetText(h);
n.SortOrderControl.SetNumber(e);
console.log(i);
$.each(n.CustomFields, function(i, e) {
console.log(i);
var value = t || !i ? null : f[e.DataName]
, dxControl = eval(e.ControlName);
dxControl.SetValue(value);
dxControl.SetIsValid(!0)
});
t || $(n.ItemCombo.GetMainElement()).find(".dms-combo-main-input").removeClass("newActivityItem");
n.TextControl.SetIsValid(!0)
}
EDIT
After more research it seems removing the eval line of code fixes the issue. For the time being I changed my code to not use eval although this still seems like a bug in the bundle process, for some reason you have these strange behaviour when using eval

Javascript weird loop with body onload

I have this file on my server: (Index.html)
<script src="script.js"></script>
Then Script.js:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxx-xxx-4xx-yxxx-xxxxyyyyxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
window.onload=doit;
function doit() {
var uuidme;
uuidme = generateUUID();
window.location.href = "/test?uuid=" + uuidme;
}
And the get varible goes crazy, it never stops changing the code which is NOT even close to what I would like.
before redirecting, check the url to see if you're already at the right spot with a uuid set. You can do this by scanning the url for the variable uuid using indexOf window.location.href.indexOf('uuid=') == -1:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxx-xxx-4xx-yxxx-xxxxyyyyxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
window.onload=doit;
function doit() {
// make sure we dont find uuid set in the url already
if(window.location.href.indexOf('uuid=') == -1) {
var uuidme;
uuidme = generateUUID();
window.location.href = "/test?uuid=" + uuidme;
}
}

Sub total and total auto compute

I just need the following:
subtotal = sum(product1,product2)
total = sum(subtotal,vat)
from code
$('input').keyup(function(){
var v = this.value, el = $(this);
if(!isNaN(v)){
var ov = el.siblings('.valid').val();
el.siblings().last().val(v*ov);
$(this).removeClass('nope').trigger('totalChange');
} else {
$(this).addClass('nope');
}
});
$(document).on('totalChange', function(){
var val1 = parseFloat($('#vat_zero_re').val(), 10);
var val2 = parseFloat($('#ve_subtotal').val(), 10);
$('#total').val(val1+val2);
});
source code : http://jsfiddle.net/4c0epamc/
Check this fiddle
Javascript
$('input').keyup(function(){
var v = this.value, el = $(this);
if(!isNaN(v)){
var ov = el.siblings('.valid').val();
el.siblings().last().val(v*ov);
$(this).removeClass('nope').trigger('totalChange');
} else {
$(this).addClass('nope');
}
});
$(document).on('totalChange', function(){
var valx=parseFloat($('#peza_locator').val(), 10);
var valy = parseFloat($('#peza_facilities').val(), 10);
$('#ve_subtotal').val(valx+valy);
var val1 = parseFloat($('#vat_zero_re').val(), 10);
var val2 = parseFloat($('#ve_subtotal').val(), 10);
$('#total').val(val1+val2);
});
In the fiddle that you specified no jquery was linked and in my fiddle to calculate the sub total i used 2 new variables named valx and valy.. check it..

jQuery Uncaught TypeError: Object[object Object] has no method 'toFixed'

Hi Guys i encounter Problem on my program which says that i have no method 'toFixed' what is the meaning or what to do to fix this?
Here is MY javascript
<script type="text/javascript">
$(document).ready(function(){
$("#datepicker").kendoDateTimePicker({
format: "yyyy-MM-dd HH:mm:ss"
});
$("#supplier_list").kendoComboBox();
$(".code_select").kendoComboBox();
//automatic computation in rows
$('[id^=qty],[id^=price],#tin_number').on('change',function() {
var index = this.id.match(/\d+/)[0];
var qty = parseInt($('#qty'+index).val());
var price = parseFloat($('#price'+index).val());
var disc = $("#discount").val();
var total = 0;
$('#total'+index).val((qty * price ? qty * price : 0).toFixed(2));
var total = 0;
$('[id^=total]').each(function(index){
total+=parseFloat($(this).val()?$(this).val():0);
});
var totalAll = $('#sum_of_total').val(total.toFixed(2));
var vatable = 0;
var vatable_amt = 0;
var totalVat = 0;
var computeDisc = 0;
if($("#tin_number").val().length != 0){
vatable = total / 1.12;
vatable_amt = vatable * 0.12;
totalVat = vatable + vatable_amt;
}else{
totalVat = total;
}
$('#vatable').val(vatable.toFixed(2));
$("#vatable_amount").val(vatable_amt.toFixed(2));
var gtotal = $("#gtotal").val(totalVat.toFixed(2));
$("#total_amt_due").val(gtotal.toFixed(2));
// Here is the line of error uncaught TypeError : Object[object object] has no method'toFixed'
});
$("#discount").on('change',function(){
var totalSales = $("#gtotal").val();
var discountedAmt = $("#discount").val();
var computeTotalDisc = totalSales - discountedAmt;
$("#total_amt_due").val(computeTotalDisc.toFixed(2));
});
//AUTO ASSIGN TO SUPPLIER INFO
$('#supplier_list').bind('change', function(){
var var_add_category ='<?php echo site_url("purchaseorder_controller/supplier_details"); ?>';
$.ajax({
type:'POST',
url: var_add_category,
data:{ id: $(this).val() },
dataType:'json',
success:function(d){
var bankname = d['bankname'];
var bankbranch = d['bankbranch'];
$("[name=spaddress]").val(d['spaddr']);
$("[name=tin]").val(d['sptinno']);
$("[name=contactperson]").val(d['pricontactname']);
$("[name=contactnumber]").val(d['sptelno']);
$("[name=bank]").val(bankname + ' - ' + bankbranch);
$("[name=account_name]").val(d['bankacctname']);
$("[name=account_no]").val(d['bankacctno']);
}
});
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate != ''){
$("#qty"+index).removeAttr('readonly');
$("#price"+index).removeAttr('readonly');
}
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate == ''){
$("#qty"+index).prop('readonly', true);
$("#price"+index).prop('readonly', true);
}
What to do pls help me guys thank you for the help in advance
gtotal is a jQuery object, not a number ?
var gtotal = $("#gtotal").val(totalVat.toFixed(2)); // returns jQuery object
$("#total_amt_due").val(gtotal.toFixed(2)); // that has no toFixed()
try:
var gtotal = totalVat.toFixed(2);
$("#gtotal, #total_amt_due").val(gtotal);
Try this:
var gtotal = +$("#gtotal").val(totalVat.toFixed(2)).val();
Then gtotal is number.
Also, you can't calculate a number that has already been .toFixed()
so you can do:
$('#vatable').val(vatable.toFixed(2));
$("#vatable_amount").val(vatable_amt.toFixed(2));
var gTotal = totalVat;
$("#gtotal").val(totalVat.toFixed(2));
$("#total_amt_due").val(gtotal.toFixed(2));
but you can't do:
var gTotal = totalVat.toFixed(2); //pretend this equaled 1000.00
var total_amt_due = gTotal + 1.toFixed(2);// this would give you 1000.001.00
or
var total_amt_due = total_amt_due.toFixed(2);//this would give you the object no method toFixed error

Categories