I am stuck trying to convert a javascript file that ran perfectly in d6 to d7, I have been searching through the info about drupal behaviours but cannot seem to find the correct manner to resolve this.
The following script returns an unexpected token error ), for the closing bracket before (jQuery).
(function($){
var VAT = 0.2;
var QUANTITY_SUFFIX = "field-po-quantity";
var PRICE_SUFFIX = "field-po-price";
var SUBTOTAL_SUFFIX = "field-po-item-st";
var VAT_SUFFIX = "field-po-item-vat";
var TOTAL_SUFFIX = "field-po-item-total";
var quantityFields;
var priceFields;
var fieldsValid = false;
function isNumber(value) {
return !isNaN(parseFloat(value)) &&
isFinite(value);
}
function validValue(value) {
return isNumber(value) &&
parseFloat(value) > 0;
}
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function decimalise(value) {
if (isNumber(value)) {
var numericValue = parseFloat(value);
return numericValue.toFixed(2);
}
}
function validateFields() {
var fieldsValid = true;
var allFields = new Array();
quantityFields = jQuery('input[id*="' + QUANTITY_SUFFIX + '"]');
priceFields = jQuery('input[id*="' + PRICE_SUFFIX + '"]');
allFields.push.apply(allFields, quantityFields);
allFields.push.apply(allFields, priceFields);
for (i=0; i<allFields.length; i++) {
var field = allFields[i];
var valueString = field.value;
if (!validValue(valueString)) {
field.style.borderStyle="solid";
field.style.border="inset 1px red";
fieldsValid = false;
} else {
field.style.borderStyle="none";
}
}
this.fieldsValid = fieldsValid;
}
jQuery(document).click(function() {
validateFields();
if (fieldsValid) {
var subTotalSum = 0;
var vatSum = 0;
var totalSum = 0;
jQuery('#field-po-items-values tbody tr:not(.content-multiple-removed-row)').each(function(){
var quantityString = jQuery(this).find('input[id*="' + QUANTITY_SUFFIX + '"]').val();
var numericQuantity = decimalise(quantityString);
var priceString = jQuery(this).find('input[id*="' + PRICE_SUFFIX + '"]').val();
var numericPrice = decimalise(priceString);
var subtotal = parseFloat(numericPrice * numericQuantity);
jQuery(this).find('input[id*="' + SUBTOTAL_SUFFIX + '"]').val(addCommas(decimalise(subtotal)));
var vat = subtotal * VAT;
jQuery(this).find('input[id*="' + VAT_SUFFIX + '"]').val(addCommas(decimalise(vat)));
var total = subtotal + vat;
jQuery(this).find('input[id*="' + TOTAL_SUFFIX + '"]').val(addCommas(decimalise(total)));
subTotalSum += subtotal;
vatSum += vat;
totalSum += parseFloat(total);
});
jQuery('input[id*="edit-field-po-subtotal"]').val(addCommas(decimalise(subTotalSum)));
jQuery('input[id*="edit-field-po-vat"]').val(addCommas(decimalise(vatSum)));
jQuery('input[id*="edit-field-po-total"]').val(addCommas(decimalise(totalSum)));
}
}
})(jQuery);
The file is being called from template.php, using drupal_add_js inserted in the top of the file, not under pre-process or anything.
I understand that the jQuery(document).click(function() { might also be causing an issue and may ultimately be the reason for the unexpected token error?
Thank you in advance
I don`t know whether your code is correct but it is highly recommended to use JavaScript in Drupal>7 this way:
(function ($) {
Drupal.behaviors.yourFunction = {
attach: function(context, settings) {
var VAT = 0.2;
var QUANTITY_SUFFIX = "field-po-quantity";
var PRICE_SUFFIX = "field-po-price";
var SUBTOTAL_SUFFIX = "field-po-item-st";
var VAT_SUFFIX = "field-po-item-vat";
var TOTAL_SUFFIX = "field-po-item-total";
var quantityFields;
var priceFields;
var fieldsValid = false;
function isNumber(value) {
return !isNaN(parseFloat(value)) &&
isFinite(value);
}
function validValue(value) {
return isNumber(value) &&
parseFloat(value) > 0;
}
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function decimalise(value) {
if (isNumber(value)) {
var numericValue = parseFloat(value);
return numericValue.toFixed(2);
}
}
function validateFields() {
var fieldsValid = true;
var allFields = new Array();
quantityFields = $('input[id*="' + QUANTITY_SUFFIX + '"]');
priceFields = $('input[id*="' + PRICE_SUFFIX + '"]');
allFields.push.apply(allFields, quantityFields);
allFields.push.apply(allFields, priceFields);
for (i=0; i<allFields.length; i++) {
var field = allFields[i];
var valueString = field.value;
if (!validValue(valueString)) {
field.style.borderStyle="solid";
field.style.border="inset 1px red";
fieldsValid = false;
} else {
field.style.borderStyle="none";
}
}
this.fieldsValid = fieldsValid;
}
$(document).click(function() {
validateFields();
if (fieldsValid) {
var subTotalSum = 0;
var vatSum = 0;
var totalSum = 0;
$('#field-po-items-values tbody tr:not(.content-multiple-removed-row)').each(function(){
var quantityString = $(this).find('input[id*="' + QUANTITY_SUFFIX + '"]').val();
var numericQuantity = decimalise(quantityString);
var priceString = $(this).find('input[id*="' + PRICE_SUFFIX + '"]').val();
var numericPrice = decimalise(priceString);
var subtotal = parseFloat(numericPrice * numericQuantity);
$(this).find('input[id*="' + SUBTOTAL_SUFFIX + '"]').val(addCommas(decimalise(subtotal)));
var vat = subtotal * VAT;
$(this).find('input[id*="' + VAT_SUFFIX + '"]').val(addCommas(decimalise(vat)));
var total = subtotal + vat;
$(this).find('input[id*="' + TOTAL_SUFFIX + '"]').val(addCommas(decimalise(total)));
subTotalSum += subtotal;
vatSum += vat;
totalSum += parseFloat(total);
});
$('input[id*="edit-field-po-subtotal"]').val(addCommas(decimalise(subTotalSum)));
$('input[id*="edit-field-po-vat"]').val(addCommas(decimalise(vatSum)));
$('input[id*="edit-field-po-total"]').val(addCommas(decimalise(totalSum)));
}
}
}
};
})(jQuery);
More info about Drupal Behaviours:
Drupal behaviors
Theming, jQuery, DRupal Behaviours
Related
var tempreture = document.getElementById("temp")
var requestWeather = new XMLHttpRequest();
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
}; requestWeather.send();
function getTemp(data) {
var tempString = "";
var temp = data.main.temp;
tempString += "<p class='weather'>" + temp + '℃' + "</p>";
tempreture.innerHTML = tempString;
tempreture.addEventListener("click", function( ) {
var ftemp = "<p class='weather'>" + changeTemp(temp) + '° F' + "</p>";
tempreture.innerHTML = ftemp;
},false);
}
function changeTemp(temp){
var tp = temp * 1.8 + 32;
var cel =Math.round(tp);
return cel;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="temp" onclick="getTemp()"></a>
How do I use the click callback handler to swap text from a different string
I want to switch between Fahrenheit and Celsius when a user clicks an element.
This is what I have done so far:
function getTemp(data) {
var tempString = "";
var temp = data.main.temp;
tempreture.addEventListener("click", function( ) {
tempString += "<p class='weather'>" + temp + '℃' + "</p>";
},false)
tempString += "<p class='weather'>" + changeTemp(temp) + '° F' + "</p>";
tempreture.insertAdjacentHTML("beforeend", tempString);
}
function changeTemp(temp){
var tp = (temp - 32) * 5/9;
var cel =Math.round(tp);
return cel;
};
I have only tried this using pure javascript. It would be great if someone can give me a hint as to what I'm doing incorrectly.
var temp = data.main.temp;
The temp is where I got the data from and is passed down to the HTML. I have done the conversion, but I don't know how to pass it back from the conversion function.
ADD the temperature data are come from
var requestWeather = new XMLHttpRequest();
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=' + data.lat + '&lon=' + data.lon);
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
}
Edit I had tried the click function, now. however, I found same issues with the return back to old value after the click.
I recommend that you validate the data that the API returns.
var tempreture = document.getElementById("temp")
var requestWeather = new XMLHttpRequest();
// global cache
var currentTemp,
currentUnit;
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
};
requestWeather.send();
function getTemp(data) {
currentTemp = typeof data === 'object' ? data.main.temp : null; // save new value in global cache
currentUnit = 'celcius';
tempreture.innerHTML = currentTemp + '℃';
}
tempreture.addEventListener("click", function() {
tempreture.innerHTML = changeTemp();
}, false);
function changeTemp() {
if(currentUnit === 'celcius') {
var tp = currentTemp * 1.8 + 32;
var fh = Math.round(tp);
currentUnit = 'fahrenheit';
return fh + '° F';
} else {
currentUnit = 'celcius';
return currentTemp + '℃';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="temp" class='weather'></span>
I want this code to replace an existing URL parameter "aspid", but what it does is adding an another id on the existing one. Can anyone help?
$(document).ready(function() {
function GetUrlValue(VarSearch) {
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for (var i = 0; i < VariableArray.length; i++) {
var KeyValuePair = VariableArray[i].split('=');
if (KeyValuePair[0] == VarSearch) {
return KeyValuePair[1];
}
}
}
var asid = GetUrlValue('aspid');
var campaign = GetUrlValue('utm_campaign');
if (asid != undefined) {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&aspid=" + asid : "?aspid=" + asid);
});
}
});
You need to call this function on every a:
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
And call the function like so:
updateURLParameter(window.location.href, 'paramName', 'Value')
complete code be like :
...
$("a").attr('href', function(i, h) {
if(h){
return updateURLParameter(h, 'aspid', asid);
}
});
...
Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');
My node.js code is below.
Basically I have a buffer called searchRes and first I get some values from it.
It is supposed to loop round "results - 1" times.
It is looping.
It prints the first 3 bits of information totally correctly and then after that (4th onwards) is always the same as the 3rd one.
I have no idea why.
results = 20;
var sSize = searchRes.slice(8,16);
sSize = parseInt(sSize,16);
lols = new Array();
while(num <= results -1 ){
var cur = num + 1;
var sres=0;
for(var i in lols) { sres += lols[i]; }
if (num == 0){
var clanRes = searchRes.slice(0, 128 + (sSize * 2));
var cLen = clanRes.slice(8,16);
cLen = parseInt(cLen,16);
var firstLen = clanRes.length;
var lastLen = clanRes.length;
}else{
var cLen = searchRes.slice(lastLen + 8, lastLen + 16);
cLen = parseInt(cLen,16);
var clanRes = searchRes.slice(
lastLen,
lastLen + 128 + (cLen * 2)
);
var abc = 1;
if (abc == 1){
var lastLen = firstLen + clanRes.length;
abc++;
}else{
var lastLen = lastLen + clanRes.length;
}
}
lols.push(cLen);
console.log('\n\nClan ' + cur + ' Details');
var clanID = clanRes.slice(0,8);
clanID = parseInt(clanID,16);
num ++;
}
I'm not sure at all about where the problem is. Is it when defining clanRes or is it in making the loop?
Thanks!
**
Updated code for #bergi
**
num = 0;
var sSize = searchRes.slice(8,16);
sSize = parseInt(sSize,16);
lols = new Array();
while(num <= 3){
var cur = num + 1;
var sres=0;
for(var i in lols) { sres += lols[i]; }
if (num == 0){
var clanRes = searchRes.slice(0, 128 + (sSize * 2));
var cLen = clanRes.slice(8,16);
cLen = parseInt(cLen,16);
var firstLen = clanRes.length;
var lastLen = clanRes.length;
}else{
var cLen = searchRes.slice(lastLen + 8, lastLen + 16);
cLen = parseInt(cLen,16);
var clanRes = searchRes.slice(
lastLen,
lastLen + 128 + (cLen * 2)
);
var abc = 1;
if (abc == 1){
var lastLen = firstLen + clanRes.length;
abc++;
}else{
var lastLen = lastLen + clanRes.length;
}
}
lols.push(cLen);
console.log('\n\nClan ' + cur + ' Details');
var clanID = clanRes.slice(0,8);
clanID = parseInt(clanID,16);
console.log(clanID);
num ++;
}
Here is a exmaple searchRes:
http://pastie.org/10075399
And an example sSize:
0000000e - hex
14 - int.
var abc = 1;
if (abc == 1){
abc is always 1 in that comparison (the value is assigned right in the line before), so it will never evaluate the else block. I assume you want to move the initialisation of the variable out of the looping.
The script works great for adding items on invoice however i cant figure how to convert the data using .toFixed(2) to show $10.00 instead of 10. I get an error every time I try to add .toFixed(2) . thank you
<script type="text/javascript">
function myFunction() {
var answer = document.getElementById('total');
var x = document.getElementById('itemprice1');
var y = document.getElementById('itemprice2');
var z = document.getElementById('itemprice3');
var w = document.getElementById('itemprice4');
var taxt = document.getElementById('taxtot');
var thetot = document.getElementById('thetot');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat("0" + x.value) + parseFloat("0" + y.value) + parseFloat("0" + z.value) + parseFloat("0" + w.value);
}
function myFunction1() {
var answer = document.getElementById('total');
var taxt = document.getElementById('taxtot');
var thetot = document.getElementById('thetot');
thetot.value = parseFloat("0" + answer.value) + parseFloat("0" + taxt.value);
if (thetot > "0") {
{
//function myFunction2()
var taxt = document.getElementById('taxtot');
var tx1 = document.getElementById('tax1');
var tx2 = document.getElementById('tax2');
var tx3 = document.getElementById('tax3');
var tx4 = document.getElementById('tax4');
var x = document.getElementById('itemprice1');
var y = document.getElementById('itemprice2');
var z = document.getElementById('itemprice3');
var w = document.getElementById('itemprice4');
var answer = document.getElementById('total');
taxt.value = parseFloat("0" + tx1.value) * ("0" + x.value) + parseFloat("0" + tx2.value) * ("0" + y.value) + parseFloat("0" + tx3.value) * ("0" + z.value) + parseFloat("0" + tx4.value) * ("0" + w.value);
}
}
}
</script>
Presumably your controls are in a form, so you can reference them simply using their name in the form. You can also convert strings to numbers using unary +:
function myFunction(formId) {
var f = document.getElementById(formId);
var answer = f.total;
var x = +f.itemprice1.value;
var y = +f.itemprice2.value;
var z = +f.itemprice3.value;
var w = +f.itemprice4.value;
var taxt = f.taxtot;
var thetot = f.thetot;
// Presumably here is where you want to use toFixed
answer.value = '$' + (x + y + z + w).toFixed(2);
}
function to_dollar_string(amount)
{
return "$" + amount.toFixed(2);
}
to_dollar_string(10);
=> "$10.00"
to_dollar_string(10.567);
=> "$10.57"