how to use Javascript "document.getelementbyid" [duplicate] - javascript

This question already has answers here:
Why won't my inputs value sum?
(5 answers)
Closed 8 years ago.
i am trying to make a maths engine with JavaScript and HTML.
Here is (http://i.stack.imgur.com/NCEa4.jpg)
The alert from the js alert() function works but the output from it is wrong:
'HTMLObject'

Value of the input field is always a string. So when you use + operator with two strings it concatenates them. If you want to add two numbers you need first to convert strings to numbers. There are multiple ways to do it, for example:
var plus = parseInt(one) + parseInt(two);
Or you can use Number(one), or another unary + operator: +one + +two, but this might look confusing.

Use 'parseInt()' function to convert those values to integers first and then add the values.

make your variable plus like this:
var plus = parseInt(one) + parseInt(two);

You need to enclose your function code in curly braces { & }.
So Use:
function Maths(){
var one=document.getElementById("fid").value;
var two=document.getElementById("sid").value;
var plus=Math.parseInt(one)+Math.parseInt(two);
alert(plus);
}
Also use parseInt() to make data type conversion to convert to int in JavaScript.
Hope it'll help you. Cheers :)!!

Will be better if you use second argument in parseInt for be sure that value will be in decimal system.
function Maths() {
var one = document.getElementById("fid").value,
two = document.getElementById("sid").value,
plus = Math.parseInt(one, 10) + Math.parseInt(two, 10);
alert(plus);
}

Related

How to get a number from HTML form and pass it to JavaScript? [duplicate]

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 7 years ago.
I am trying to calculate Body Mass Index by receiving Weight and Height from HTML form and passing it to JavaScript code by .getElementById();. But, as far as I understand, type of data received from form is "string" and I need to receive a "number". How can I solve this problem?
Use parseInt().
var a = "10";
var b = parseInt(a);
See : http://www.w3schools.com/jsref/jsref_parseint.asp
var a = document.getElementById("whatever").value;
// You can use any 3
+a; // Unary Operator
parseInt(a, 10); // parseInt with radix 10
Number(a);
you can use function parseInt(string) that Convert string into int .Now in your senario :-
var weight_str = document.getElementByID("weight");
var weight_int = parseInt(weight_str);
this will give you the result.

How i can place each number on an index in array, [duplicate]

This question already has answers here:
How to convert an integer to an array in PHP?
(4 answers)
Closed 8 years ago.
I have 23681 its not string but integer , i want to make an array by placing each number on an index in php or javascript any guide would be appreciated
[0]=>2
[1]=>3
[2]=>6
[3]=>8
[4]=>1
Javascript
result = (23681).toString().split("").map(Number);
You can use str_split():
$array = str_split($yourNumber);
Your int will be casted to string automatically. So no implicit casting needed here.
Another javaScript solution without string conversion
var number = 12345, result=[];
while(number>0) {
result.push(number % 10);
number = Math.floor(a / 10);
}
result.reverse()
quick and easy:
$your_number_arr = array_map('intval', str_split($your_number));
edit: integer conversion
You should be more specific. I don't know if you need this in Javascript or PHP, but here it is in php:
$str = ((string)$int);
$array = str_split($str);

Getting the first item in an [word, word] [duplicate]

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow

Dynamic key names [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 9 years ago.
I am trying to generate object elements dynamically from a loop by passing an integer in the initial i.e common prefix of the elements.
Like this:
if(inventory.inventory_obj.length){
obj.inventory_length = inventory.inventory_obj.length;
for(var x=0; x < inventory.inventory_obj.length; x++){
obj.warehouse_+x = inventory.inventory_obj[x].warehouse;
obj.name_+x = inventory.inventory_obj[x].name;
obj.space_+x = inventory.inventory_obj[x].space;
obj.cost_+x = inventory.inventory_obj[x].cost;
obj.quantity_+x = inventory.inventory_obj[x].quantity;
obj.level_+x = inventory.inventory_obj[x].level;
obj.status_+x = inventory.inventory_obj[x].status;
obj.deleted_+x = inventory.inventory_obj[x].deleted;
}
}
Doing the above I get "Invalid left-hand side in assignment" error
I have tested the inventory.inventory_obj through console.log(inventory.inventory_obj) and verified that it has the needed values.
Other tries I have made include
obj.warehouse_+""+x = inventory.inventory_obj[x].warehouse;
obj.warehouse+"_"+x = inventory.inventory_obj[x].warehouse;
obj.warehouse_+x.toString() = inventory.inventory_obj[x].warehouse;
obj.warehouse.concat("_"+x+"") = inventory.inventory_obj[x].warehouse;
//Eliminating the underscore
obj.warehouse+x = inventory.inventory_obj[x].warehouse;
All the above failed.
Please someone help me understand what I am doing wrong.
To create the property name dynamically, use the square bracket notation:
obj['warehouse_' + x] = nventory.inventory_obj[x].warehouse;
Your can't have + in the name obj.warehouse_+x and all other instances like that.
You need to use: obj["warehouse_" + x] for dynamic object key names.
For concatenation try using:
obj["warehouse_" + x] = obj["warehouse_" + x] + inventory.inventory_obj[x].warehouse;
There is no concatenation operator for objects like there is for strings or numbers (+=).
Although the language won't accept arithmetic names unless you are actually making a string out of it, I think you will have better semantic by using arrays instead of many simlar-named variables.
For example, if there is many indexed obj.warehouse, you should initialize it as an array:
obj.warehouse=[];
Then, to put something into it:
obj.warehouse[x] = inventory.inventory_obj[x].warehouse;
It will be easier for you to access it later because you won't have to concatenate every time you want to access a warehouse. Also, as long as there are "concatenating" accesses, debugging can be a pain whenever something is renamed.

Combining retrieved values with javascript and jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I Convert a String into an Integer in JavaScript?
I have a select element that contains options for products. What I want to achieve is when they pick an option the price on the page automatically adjusts. I have figured out how to retrieve those values but when I combine them it just puts two numbers together instead of actually adding them.
For example instead of outputting 60 when I have 50 + 10 it outputs 5010.
My code:
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Is there a way I can convert them both to integers so the operation actually goes through?
Thanks in advance!
Use parseInt
$('.product_options').change(function(){
var base_price = parseInt($('#base_price').html(), 10); // 10 as second argument will make sure that base is 10.
var add_price = parseInt($(this).find("option:selected").data('price'), 10);
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Try:
var base_price = +$('#base_price').html();
var add_price = +$(this).find("option:selected").data('price');
See the mighty: Mozilla's Arithmetic Operators Reference - Unary Negation
Any values you pull out of the DOM are going to be strings, and need converting into number types before you can do mathematical operations with them.
parseInt( ... ) is a built in javascript function that converts a string into an integer, if the string consists of digits only.
If you need a decimal number, you can use parseFlaot.
var new_price = parseInt(base_price)+parseInt(add_price);
// new_price is now set to the sum of `base_price` and `add_price`
Use parseFloat or parseInt
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = parseFloat(base_price) + parseFloat(add_price);
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Yes there is.
intval = parseInt(string)
is what you're looking for.

Categories