Why is my function outputting 0 (zero)? - javascript

This code is supposed to calculate two user inputs by multiplying them. However, the output is consistently 0 instead of would normally be expected ie 5*5=0. I am not sure why this is happening. Am I not passing the variables into the function correctly? I feel like I might not be properly understanding value vs. reference (I am currently learning javascript)
var x = document.getElementById("a").value;
var y = document.getElementById("b").value;
var button = document.getElementById("button");
button.addEventListener('click', function() {
calculator(x,y);
}, false);
function calculator(a,b) {
var output = a * b;
document.getElementById("answer").innerHTML = output;
console.log(output);
}

Omit the value capture, just grab the elements:
var x = document.getElementById("a");
var y = document.getElementById("b");
Then use the values as the function parameters.
button.addEventListener('click', function() {
calculator(x.value, y.value);
}, false);
You were grabbing the values when they were empty and passing those to the function.
DEMO

It could be that the script is treating the values as strings, try using parseInt(a) * parseInt(b)

Related

How to fix this 'undefined' when i try to display the sum in the element "pro1'

Im trying to get the value from the element 'amt1' which increases everytime i onclick a button and display it on the element 'pro1'. however, i am receiving the value 'undefined' im really new to javascript. hope someone could help me. thank you in advance!
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
var price1 = document.getElementById("amt1").value;
return price1;
};
}(0);
var total1 = price1*parseFloat(119.90);
function displayPrice(){
document.getElementById('pro1').innerHTML = total1;
}
price1 is a local variable in the lexical scope of the function returned by sum function. It's value is not available in the outer scope when you try to multiply it by 119.90.
You can get the price from the element amt1 dynamically inside displayPrice function instead.
Also if amt1element is not an input then you should use .textContent property of the element instead of .value:
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
};
}(0);
document.querySelector('button').addEventListener('click', add1)
function displayPrice(){
var price = parseFloat(document.getElementById("amt1").textContent);
var total = price * 119.90;
document.getElementById('pro1').innerHTML = total;
}
document.querySelectorAll('button')[1].addEventListener('click', displayPrice)
<p id="amt1">0</p>
<button>Add</button>
<br><br>
<button>Total</button>
<p id="pro1"><p>

Jquery insert function params into selector

I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");

Locate the Greatest Number in JS

I am attempting to enter in 3 number input fields in my HTML, listed below:
HTML File-
<label for="num1">Enter number 1.</label><input type="text" size="20" id="num1">
<label for="num2">Enter number 2.</label><input type="text" size="20" id="num2">
<label for="num3">Enter number 3.</label><input type="text" size="20" id="num3">
<div id="greatestbutton" class="button">Click here to get the Greatest Number!</div>
<div>The greatest number is <span id="num1 || num2 || num3"></span></div>
Once these number have been entered, I want to ensure that they are indeed numbers and not letters and I wanted to take the greatest of those that have been entered:
JS File-
var button = document.getElementById("greatestbutton");
button.onclick = function greaterNumber(num1, num2, num3) {
var a = parseFloat(num1);
var b = parseFloat(num2);
var c = parseFloat(num3);
var greatest = Math.max(a, b, c);
return greatest;
}
}
I can 'see' the 'button' accept the click, but I am unable to get it to return anything, let alone the greatest number.
Any help for this newbie would be greatly appreciated!!
Thanks!!!
Change the result element's id first:
<div>The greatest number is <span id="result"></span></div>
Then modify the button click function a little:
var button = document.getElementById("greatestbutton");
button.onclick = function() {
var num1 = document.getElementById('num1').value; // get value from inputs
var num2 = document.getElementById('num2').value;
var num3 = document.getElementById('num3').value;
var a = parseFloat(num1);
var b = parseFloat(num2);
var c = parseFloat(num3);
var greatest = Math.max(a, b, c);
document.getElementById('result').innerHTML = greatest; // set value for result
}
You aren't passing any values to the function greaterNumber, it doesn't just take values automatically. In this case you want to give it the values from the input fields, you can do that in a lot of ways, one of them being:
var button = document.getElementById("greatestbutton");
button.onclick = function greaterNumber() {
var a = parseFloat(document.getElementById('num1').value); // get value
var b = parseFloat(document.getElementById('num2').value);
var c = parseFloat(document.getElementById('num3').value);
var greatest = Math.max(a, b, c);
return greatest;
}
return simply returns the value to whatever you call it from, in this fiddle i used alert instead just to prove that it works http://jsfiddle.net/NMys3/
A couple of points:
1) You seem to be assuming that the form's input values will be passed automatically as arguments to the event callback. They will not - all that's passed to the event callback is the event object itself. You need to grab those values manually, yourself.
2) You can't merely return the value from the event callback - you need to do something with it.
3) You don't say what should happen if one or more values are not numbers; presumably a message should appear or something, which is what I've assumed.
4) Not sure what you meant by that weird id attribute on the span; it seems like you've made a lot of assumptions about how code works here. Give it an ID of something like "max_num".
Try:
document.querySelector('#greatestbutton').addEventListener('click', function() {
var num_nums = 3, nums = [];
for (var i=0; i<num_nums; i++) {
var val = document.querySelector('#num'+(i+1)).value;
if (!parseFloat(val)) { alert('bad input!'); return false; }
nums.push(val);
}
document.querySelector('#max_num').innerHTML = Math.max.apply(null, nums);
}, false);
Note I have also...
1) Modernised the code slightly; it's better to register events using addEventListener (for reasons that are beyond the scope of this question) and I've used the ECMA5 jQuery-like method querySelector, which finds elements by CSS-style syntax
2) Made it dynamic for N numbers; your code is hard-coded to three, and requires more lines of code should this number be increased at any point

Javascript, counting in seconds - adding a point each time

So I am working on a project of mine and I'd like some help.
I'd like javascript to be able to count in seconds, each second it'd add a preset amount of points.
var total_points = 0
var points_per_click = 1
var points_per_second = 0
function points_per_second() {
docuement.getElementById("current_points").innerHTML("Current Points: " + total_points);
//insert here?
}
I would also like the points_per_second to be able to add into the total_points var. Thanks!
docuement is spelt "document", .innerHTML is not a function call (set it like a variable) & variables and functions share the same namespace, i.e. don't set a variable points_per_second and then declare a function of the same name.
Once you have your syntax errors sorted, you were probably looking for setInterval.
var total_points = 0;
var points_per_click = 1;
var points_per_second = 2;
function update_display(){
var el = document.getElementById("current_points");
el.innerHTML = "Current Points: " + total_points;
//insert here? ... No
}
var ticker = setInterval(function(){
total_points += points_per_second;
// ... or whatever your intended logic
update_display();
}, 1000);
jsFiddle

jQuery on variable change, update textbox

In jQuery, is is possible to check if var x = [] changes, and then add the contents of the array to a textbox.
So if x contains ["1","2","3"]. My textbox textbox1 value will be "1","2","3"
You could do something like this to avoid using a watcher:
var Data = (function () {
var _x = [],
$textbox = $("#myTextbox");
return {
getX: function () {
return x;
},
setX: function (x) {
_x = x;
// Setting 'x' triggers an update
$textbox.val(x.join(","));
}
}
}();
And then set the value of x using Data.setX(x) and get it using Data.getX().
var myString = myArray.join(',');
$('#textbox1').val(myString);
Don't know about watching a variable for a change, unless you create an object that has an "onChange" event, but to show the values in the textbox use this...
$("#textboxID").val(x.join(","));
The easiest thing would be to have an update function with the above code and just call that everywhere you change the value of x.
if ($.inArray(x, [1, 2, 3]) != -1) {
$('#textbox1').val(x);
}

Categories