Locate the Greatest Number in JS - javascript

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

Related

Is there any way to add value of two <h> tags using jquery?

I have two <h4> tags, one which contain price, and another contains percentage value. I need to find the percentage and set into new <h4> tag.
I tried to calculate but which return NaN instead. I tried alert(parseFloat(price)+parseFloat(percent)) which return concatenated result, not the sum(for just testing).
I tried following, value is assigned based on checkbox click.
$("#checkbox1").click(function () {
if ($(this).prop("checked")) {
var price = $("#tex2").text();
var percent = $("#percent").text();
price = parseFloat(price);
percent= parseFloat(percent);
var dis_price;
dis_price = parseFloat(dis_price);
dis_price = price-(percent/100)*price;
$('#tex1').text(dis_price);
}
else {
$("#tex1").text("test");
}
});
I want to get calculated value instead of NaN. Please find me way to solve this problem.
without jquery it will be simpler (the + make implicit cast string to number)
var price = +tex2.innerText;
var per = +percent.innerText;
tex1.innerText = price-(per/100)*price;
function make(check) {
if(check.checked) {
var price = +tex2.innerText;
var per = +percent.innerText;
tex1.innerText = price-(per/100)*price;
} else {
tex1.innerText = 'test';
}
}
<input type="checkbox" onchange="make(this)">Click</button>
<div>
<h id="tex2">10</h>
<h id="percent">20</h>
<h id="tex1"></h>
</div>
A math operation on an undefined value will return NaN. Make sure your referenced values are not undefined.

Why is my function outputting 0 (zero)?

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)

Placing code in my Javascript array

I have the following problem,
I have made a form with alot of input fields. Where if the user types a 1 it will show the price immediately next to it. My code for this is this:
var priceMargherita = 7;
var numPizzaMargheritaInput = document.getElementById('countMargherita');
var priceMargheritaLabel = document.getElementById('totalMargherita');
function onNumPizzaMargheritaInputChange(e){
var totalMargherita = priceMargherita * parseInt(e.target.value);
var formattedPrice = '\u20ac '+totalMargherita.toFixed(2);
priceMargheritaLabel.innerHTML = '';
priceMargheritaLabel.appendChild(document.createTextNode(formattedPrice));
}
numPizzaMargheritaInput.addEventListener('change', onNumPizzaMargheritaInputChange, false);
and it places the price like this:
<td>Pizza Margherita</td>
<td><input type="number" id="countMargherita" class="formnumbers" name="PizzaMargherita" onChange="validateForm(this)" min="1" max="99"/></td>
<td><span id="totalMargherita"></span></td>
Now my problem is that i have 11 products like this Pizza Margherita. And at the moment i have 11 pieces of code like the top one. I think this can be done in an array since the only things that change are some names.
Correct me if i'm wrong since im nowhere experienced in JS nor Arrays.
Any help is greatly appreciated!
For me, the simplest way to do it is to NOT use arrays or ids.
If you can change the html, you should add the price as a data-attribute, and then you can have a generic code :
<td>Pizza Margherita</td>
<td><input type="number" class="formnumbers" name="PizzaMargherita"
onChange="changeTotalFromCount(this)" min="1"
max="99" data-unitPrice="7" /></td>
<td></td>
JS :
function changeTotalFromCount(input) {
var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
var count = input.value;
var price = unitPrice * count;
var formattedPrice = '\u20ac ' + price.toFixed(2);
var label = input.parentNode.nextElementSibling;
label.innerHTML = '';
label.appendChild(document.createTextNode(formattedPrice));
}
Rather than arrays, I think the word you're looking for is loops. Here is a way to factor your program using an object and a loop:
var prices = {
Margherita: 7,
Hawaiian: 7,
NewYork: 8
};
for (var pizzaType in prices) {
var inputElement = document.getElementbyId('count' + pizzaType);
var labelElement = document.getElementbyId('total' + pizzaType);
inputElement.addEventListener('change', function(event) {
var total = prices[pizzaType] * parseInt(event.target.value);
var formattedPrice = '\u20ac ' + total.toFixed(2);
labelElement.innerHTML = '';
labelElement.appendChild(document.createTextNode(formattedPrice));
}, false);
}
I chose to use an anonymous function instead of a named one, as this is the most common practice with event listeners.
Make a more generic function for calculating your price, like onNumPizzChange which takes the base element name, e.g. 'Margherita'. In this function, extract your element like
var inputElm = document.getElementById('count'+elmBase);
then set up your events by wrapping this function with another like so:
document.getElementById('numPizzaMargheritaCount').addEventListener('change', function(){ onNumPizzaChange('Margherita')}, false);
Does that make sense?
Good luck!
An array isn't the most efficient way to solve the problem. You'd be better off with a more generalised function that has the necessary information (the event, the price, and the ID of the element to display the price) as parameters. Then use an array of objects to initialise everything. Something like this:
var pizzas = [
{
pizza: 'margherita',
price: 7,
input: 'countMargherita',
label: 'totalMargherita'
},
{
pizza: 'pepperoni',
price: 10,
input: 'countPepperoni',
label: 'totalPepperoni'
}
]
function calculatePrice(e, price, label) {
var total = price * parseInt(e.target.value);
var formattedPrice = '\u20ac '+total.toFixed(2);
var outputElement = document.getElementById(label);
outputElement .innerHTML = '';
outputElement .appendChild(document.createTextNode(formattedPrice));
}
Then iterate over that pizzas array to bind everything up:
for(var i = 0, l = pizzas.length; i < l; i++) {
(function(pizza) {
document.getElementById(pizza.input).addEventListener('change', function(e) {
calculatePrice(e, pizza.price, pizza.label);
}, false);
})(pizzas[i]);
}
The above uses a closure to avoid issues due to JavaScript's variable scoping; i is scoped to the function scope since there isn't block-level scoping. Since the event handler is essentially a deferred action, the value of i when that executes will also be the last value of i if you don't use one.

jQuery val() Issue

I am using .val() to set the values in HTML. My code is like this:
function first(){
var a=1;
$("#pg_textbox").val(a);
}
Now this code sets vales in my hidden HTML id 'pg_textbox':
<input type="hidden" id="paging_textbox">
On the second function call, it is like this:
function secound(){
var b=2;
$("#pg_textbox").val(b);
}
Now when I use:
$("#pg_textbox").val();
to get the value of '#pg_textbox' i am getting output is
2
It is replacing the values. I want my output like:
1,2
How can I get this output without replacing the value?
Thanks.
When you call .val(b), you do reset the entire value of the textbox. Calling .val() will only retreive what's in the textbox, it has no recollection of past values.
You'll need to update your setter:
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);
Try this code
var b=1;
var old_val=$("#pg_textbox").val();
$("#pg_textbox").val(old_val+" ,"+b);
You mean you're adding values to the input type, and don't want them to be replaced?
Well here's what you need to do then.
You need to make another hidden input type which will store the sum.
<input type="hidden" id="backup"/>
function first(){
var a=1;
$("#pg_textbox").val(a);
$("#backup").val(a);
}
function second(){ // Your second function
var b=1;
var sum = $("#backup").val()+b;
var old_val = $("#pg_textbox").val();
$("#pg_textbox").val(old_val+','+sum);
}
Also, you can continue this series with third, fourth, and so on...
This is what you're after.
var a = 1,
b = 2;
$("#pg_textbox").val(a + ', ' + b);
Although my code is technically correct, I can't imagine any practical application for it. Since you want to output some comma-separated values, it might be wiser to enter your values in an array, e.g.,
var yourValues = [1,2],
output = yourValues.toString();
$('#pg_textbox').val(output);​
Check if there's a value already, if there is, concatenate the values...
var newVal = 2;
var prevVal = $("#pg_textbox").val();
if (prevVal == '')
{
$("#pg_textbox").val(newVal);
}
else
{
$("#pg_textbox").val(prevVal + ',' + newVal);
}
Update this:
var b=2;
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);

Form value addition with js

I'm trying to write a order form that shows the value of the selected items automatically. The backend is already complete, and on the front end each field, all radio / checkbox, look like this:
<input type="radio" name="shirt-size" value="shirt_size_m[18]" />
'18' being the price, everything else being irrelevant to the front end price calculation. I cannot change the naming convention, so I need to get the value between the brackets on all the <input>s on the page (or below the parent ID), add them together (on update), and append the value to another ID. Jquery is already in use on the site if that makes thongs easier.
I just need to be pointed in the right direction as my JS experience is limited to examples and minor customizations :)
Try using a simple regular expression with Javascript's replace, to replace all non-numeric characters with the empty string:
var str = "shirt_size_m[18]";
var theNumber = parseInt(str.replace(/[^0-9]/g, ''));
alert(theNumber);
Demo: http://jsfiddle.net/XvTaY/1/
You could try something like this:
function calculate_sum(form_id) {
var $form = $(form_id);
var sum = 0;
$checkbox_and_radios = $form.find('input[type=checkbox], input[type=radio]').each(function(){
sum += parseInt($(this).val().match(/^[^\[]+\[(\d+)\]$/)[1]);
});
return sum;
}
$(function(){
$("#id_of_the_form").find('input[type=checkbox], input[type=radio]').change(function(){
var sum = calculate_sum("#form_id");
// I don't know the type of your element containing
// the sum, so I put multiple solutions here:
// some input element
$('#another_id').val(sum);
// or another element
$('#another_id').html(sum);
// I'm assuming you don't really mean append
// If you're sure you want to append: (but then the old value won't be deleted)
$('#another_id').append(sum);
});
});
u can use:
var v;
v = $('#input-identifier').val();
v = v.split("[");
v = v[1];
v = v.split("]");
v = v[0];
// now v has the number

Categories