Problem With Variables And Objects - javascript

I have 3 TextFields, called txtUSD, txtEUR, txtAUS. And a PopupList with the same values, minus the txt part, but I need to form the names of the TextFields to use based on the selection that the user made. So I've done this:
function btConvert_Click(event)
{
var amount = document.getElementById("txtAmount").value;
var rates = document.getElementById("lstConvertTo").value;
var from = "txt" + document.getElementById("lstFrom").options[document.getElementById('lstFrom').selectedIndex].text;
var to = "txt" + document.getElementById("lstConvertTo").options[document.getElementById("lstConvertTo").selectedIndex].text;
var curr_from = document.getElementById(from).value;
var curr_to = document.getElementById(to).value;
if(curr_from > curr_to)
{
amount * rates;
} else {
amount / rates;
}
alert(result);
}
But every time I try it I get this error:
mobile/main.js line 215: Result of expression 'document.getElementById(from)' [null] is not an object.
How should I make it?

From the error you're getting, it looks like there's a bug when generating the from variable.
You should consider storing document.getElementById('lstFrom') into it's own var, for brevity.

Related

Javascript count two variables goes wrong

I am busy with making a kind of invoice system, where the user can make invoices very easily. Now I am at the point where I have to count up, per product, three different variables/items, but instead of counting them up, my javascript code puts it like text (with the + operator).
Example:
selectmenu 1 = option 0 (where VAT = 8.50 euro's)
selectmenu 2 = option 1 (where VAT = 12.76 euro's)
Now the output has to be (8.50+12.76)= 21.26
The output in my situation is = 8.5012.76
My (partial) javascript code:
$("select#product").on("change", function (e) {
var $row = $(e.target).closest('.productitem');
var selVal = $row.find('#product').val();
var totalvat;
var currentVat = $('#totalvat').val();
var NLhoog = 1.21;
var price0EXC = 40.49;
var price0INC = (price0EXC * NLhoog).toFixed(2);
var price0VAT = (price0INC - price0EXC).toFixed(2);
var price1EXC = 60.74;
var price1INC = (price1EXC * NLhoog).toFixed(2);
var price1VAT = (price1INC - price1EXC).toFixed(2);
if (selVal === "0") {
$row.find("input#vat").val(price0VAT);
$row.find("input#priceEXC").val(price0EXC);
$row.find("input#priceINC").val(price0INC);
totalvat = (currentVat + price0VAT);
$('input#totalvat').val(totalvat);
} else if (selVal === "1") {
$row.find("input#vat").val(price1VAT);
$row.find("input#priceEXC").val(price1EXC);
$row.find("input#priceINC").val(price1INC);
totalvat = currentVat+price1VAT;
$('input#totalvat').val(totalvat);
}
});
I have let the unimportant part of the code away.
If you know what I am doing wrong, please let me know :)
Think this may help?
var currentVat = parseFloat($('#totalvat').val());
You are using var currentVat = $('#totalvat').val(); to get the value from an input I assume? This is a string which will need to be parsed at some to a relevant datatype. When + is used with a string the compiler performs concatenation.
Try something like:
var currentVat = parseFloat($('#totalvat').val());
Or do it later on with:
parseFloat(currentVat);
As you're using numbers as currency I'd consider adding the suffix .ToFixed(2) at the end, and maybe some other formatting

issues with a global array and sending json data

var x = document.getElementsByTagName('button');//return button array
//arrays
var entry_age = [];//age
var entry_relation = [];//relation
var entry_smoker = [];//smoker
//add button clicked
x[0].addEventListener("click", function(){
var age = document.getElementsByName("age")[0].value;//pull age from box
var relation = document.getElementsByName("rel")[0].value;//pull relation
let smoker = document.querySelector('[name=smoker').checked;
//check relation
if(relation === "")
{
alert("please select a realation");
}
//check to see if age < 0
if(age < 0 || age === " ")
{
alert("age not applicable");
}
//add data to arrays
entry_age.push(age);
entry_relation(relation);
entry_smoker(smoker);
alert(entry_age[0]);
});
x[1].addEventListener("click", function(){
var age = JSON.stringify(entry_age);
alert(entry_age[1]);
document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);
});
I'm trying to store a value in entry age dynamically and convert that to JSON and display it in a only thing is I can't get the data to store in the array, how do I get the array to work globally? At this point I'm pretty sure it's my array but do y'all see anything wrong with the JSON. For debugging purposes I used an alert with the array index and the one in the second function is coming up as unidentified It is to return to a pre tag with the class name of debug. You guys have really helped me out a lot with this project.

Save and print list with array

I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.

Filling arrangement from a database

I need to fill an array with each of the values ​​for "name" and "nickname" taken from a SQLITE database and show it in an alert.
This is for a project written in JavaScript in titanium appcelerator.
This is the code:
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push = {
name: name,
nickname: nickname
};
fightersRS.next();
}
alert(setFighters);
The idea is that the alert displays all comma separated values, for example:
"muhammad ali, rocky balboa, ten shin han, etc ...."
How I can do it? my code does not work.
Change your code as follows
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
var nickname = fightersRS.fieldByName('nickname');
setFighters.push({"name": name, "nickname": nickname}); //This is the correct syntax for pushing an element to the array
fightersRS.next();
}
You can display the elements using a for loop as follows
for(var i=0; i <setFighters.length;i++){
alert("Name = " + setFighters[index].name + " Nickname= " + setFighters[index].nickname);
}
If you want to display their name with comma, try the following
var fightersRS = db.execute('SELECT * FROM fighters');
var setFighters = [];
while (fightersRS.isValidRow())
{
var name = fightersRS.fieldByName('name');
setFighters.push(name);
fightersRS.next();
}
var fighters = setFighters.join(",");//Joining the array elements with comma
alert(fighters); //Will display all names with a comma
Look at javascript join method
Use a for loop or inside the while loop only create a string appending all the values with comma.
Fetching all the data from an array with comma is not possible.
Here's an asccociative array example from stack over flow .. you can have your own for loop or use the while loop you are creating
Associative array and fetching data
Thanks

how to get a number form value and turn it into string javascript

I want to turn a number I get from a form into a string and combine it with another string, but I receive this:
windows.location='multiSet?type=multi'Number
instead I want to get this:
windows.location='multiSet?type=multiNumber'
Note that the difference is the position of the ' mark is before Number and I want it after it..
All i see in other post is how to put a string as a number not viceversa.
var singleMultiContainer = document.getElementById("singleMultiContainer");
var singleMultiValue = singleMultiContainer.value;
var nextButton = document.getElementById("nextButton");
var multipleSetWindow = "window.location='multiSet.html?type=multi'";
var singleSetWindow = "window.location='SampleInfo.html?type=single'";
var containerCuantity = document.getElementById("containerCuantity");
function setContainers(){
singleMultiValue = singleMultiContainer.value;
containerCuantityValue = parseInt(containerCuantity.value);
if (singleMultiValue == "multi"){
//alert("Multi");
document.getElementById("nextButton").setAttribute("onclick", multipleSetWindow+containerCuantityValue);
} else if (singleMultiValue == "single") {
document.getElementById("nextButton").setAttribute("onclick", singleSetWindow);
}
}
singleMultiContainer.onchange = function(){
setContainers();
}
Don't use setAttribute to define event handlers. And you don't need to parse the value as you want to put it back in a string.
Change
document.getElementById("nextButton").setAttribute("onclick", multipleSetWindow+containerCuantityValue);
to
document.getElementById("nextButton").onclick = function(){
window.location='multiSet.html?type=multi'+containerCuantity.value;
}

Categories

Resources