Get max from series of input fields - javascript

I have a series of input fields. I never know how many, so I need to get the value from a class. In this case the class is .total.
The bestresult is a text field that gets it's value from mysql, but I want it to be changed manually or by the highest value from the other text fields.
This is the code. Does not work obviously, but maybe you get the idea of what I want to do.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input.total').change(function()
{
var max = $('.total').max();
$('#bestresult').attr("value", max);
});
</script>
<body>
<form>
<input type="text" name="bestresult" id="bestresult" class="total" value=""><br>
<input type="text" name="resultat[100][total]" class="total" value=""><br>
<input type="text" name="resultat[121][total]" class="total" value=""><br>
<input type="text" name="resultat[130][total]" class="total" value="">
</form>
</body>
</html>

The solution is very simple. Try this:
$('input.total').change(function()
{
var max = 0;
$('.total').each(function(){
if(parseFloat($(this).val()) > max ) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
But if you have multiple textboxes, you should keep track of the max value and update every time change event is triggered to achieve better performance.
var max = 0;
// get the max for the first time
$(document).ready(function () {
$('.total').each(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
$('input.total').change(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
$('#bestresult').val(max);
});

First, you should have your script at the end of your body, in order to have the elements defined when you bind the change event.
Then, you'd better filter the input, to exclude the one containing the max. You can use this selector : input.total[id!=bestresult].
And it would be better to bind also the keyup event, so that the max is updated without the user having to click outside.
Thus, you can have this code :
$('input.total[id!=bestresult]').on('blur change keyup', function(){
$('#bestresult').attr("value", Math.max.apply(null, $('.total[id!=bestresult]').map(function(){
return parseFloat(this.value)}).slice().filter(function(i, v){return v==v})
));
});
Demonstration

Related

javascript confirm box with if statement

I'm trying to build a jacvascript running total calculator which allows the user to specify inputs which are sued to calculate a (sum) total which is shown on screen.
Before the user makes a change to the input I want to have a confirm box which allows the user to select okay (which leads to the new total being calculated) or cancel.
I've inserted the confirm box code with an IF statement into the GetTotal function but it doesn't seem to be working. Every time the new total is calculated irrespective of whether the user selects okay or cancel. Any help greatly appreciated. Mike
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.1/js/bootstrap-dialog.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<script>
var input1 = 5555;
var input2 = 666;
$(document).ready(function() {
document.getElementById("input1").value = input1;
document.getElementById("input2").value = input2;
GetFirstTotal();
});
function GetFirstTotal() {
var total = 0;
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
function GetTotal() {
var total = 0;
BootstrapDialog.confirm('Are you sure you want to do this?');
if(confirm("text")==1)
{
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
else {}}
</script>
TOTAL:
<div id="chkTotal"></div>
<br>
<input type="text" name="input1" id="input1"/>
<input type="button" value="Change X" onclick="GetTotal(this)"/>
<br>
<br>
<input type="text" name="input2" id="input2"/>
<input type="button" value="Change Y" onclick="GetTotal(this)"/>
The default Javascript confirm() function should return a boolean value, so you should just be able to use :
if(confirm('Are you sure you want to do this?'))
{
// Do these things
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
However, it appears that you are using the BootstrapDialog plug-in, which seems to operate a bit differently and accepts a callback to check the value that was entered :
So your code would likely look something like this, if you wanted to use it exclusively as a confirmation option :
BootstrapDialog.confirm('Are you sure you want to do this?', function(result){
// If result is true, then the user confirmed the message
if(result) {
// Do work here
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
});

Clearing the field of a form with a button

Sounds easy probably, but not for a beginner programmer :)
I have a simple 3 field form with a submit button and a clear button. This is for a homework assignment, and we have been tasked to get the "Clear Fields" button to work properly. Here are more specific instructions:
"Add the JavaScript code for an anonymous function that's stored in a variable named clear. The function should clear the text boxes by using the $ function to get a Textbox object for each text box and then setting the value property of the textbox to an empty string. Then, add a statement in the onload event handler that attaches the clear function to the click event of the Clear Entries button."
I was able to add the statement to the onload event handler:
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
But it is the other part I am having problems with.
Add the JavaScript code for an anonymous function that's stored in a variable named clear:
var clear = function () {
Object.Method
}
Here is my full code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
var clear = function () {
miles.Text = String.Empty
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<label> </label>
<input type="button" id="clear" value="Clear Entries"><br>
</section>
</body>
</html>
And here is the code we were supplied with to work off of:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
</section>
</body>
</html>
You've got several issues going on:
You're mixing Javascript and jQuery in ways that don't quite work.
jQuery's methods and objects work differently than "pure"
Javascript, so be mindful of that.
The window.onload doesn't work the way you've got it. To be
consistent, do it the jQuery way with a $(document).ready() method
instead.
You're missing the # indicator on your jQuery IDs. This is
imperative or it won't find the ID of the elements you're calling.
It looks like you're mixing VB/C# code in with your javascript, such
as the String.Empty call, etc. Those objects/methods work from the
server and not in Javascript, so that's another issue (it's been a
while since I've worked in C#, so double check me on that).
Here's my solution below. I tweaked a few things to help with what I think you're going for (such as clearing ALL fields with the "Clear" button instead of just the miles field).
I understand you're a student, so don't make it a habit of coming here and trying to find people to do your homework for you. You did provide an attempt at some code, and there were a number of issues in it, so I chose to rectify them for you and explain the reasons since there were so many. Others are not as generous, but I was a struggling student once, too, so I get it when you're banging your head against the wall. :-)
$( document ).ready( function () {
var clear = function () {
miles.value = "";
gallons.value = "";
mpg.value = "";
}
var calculateMpg = function () {
var miles = parseFloat($("#miles").val());
var gallons = parseFloat($("#gallons").val());
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");
}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");
}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");
}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("#mpg").val(mpg.toFixed(1));
}
}
$("#calculate").bind("click", calculateMpg);
$("#miles").focus();
$("#clear").bind("click", clear);
});

Calculate form inputs onChange

I have a dynamic form that is being generated based on what the user adds to the cart.
For example, the form will looks something like this,
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Form</title>
</head>
<body>
<form action="" name="cart" id="cart">
<input type="text" name="sku1">
<input type="text" name="sku2">
<input type="text" name="sku3">
<input type="text" name="sku4">
<input type="text" name="sku5">
<div class="sum" id="sum"> Total: {SUM SHOULD SHOW UP HERE)</div>
<button name="submit">Send</button>
</form>
</body>
</html>
But those input fields are generated automatically and may be more or less than 5 fields.
How to calculate those input SUM value and output to SUM div without page refresh?
JavaScript/jQuery?
$('button[name="submit"]').click(function () {
var sum = 0;
$('#cart input[name^="sku"]').each(function () {
var val = isNaN(+this.value) ? 0 : +this.value;
sum += val;
});
$('#sum').text(sum);
});
Or
var inp = $('#cart input[name^="sku"]');
inp.change(function () {
var sum = 0;
inp.each(function () {
var val = isNaN(+this.value) ? 0 : +this.value;
sum += val;
});
$('#sum').text(sum);
});
Attribute Starts With Selector [name^="value"]
.change()
isNaN()
You can use the onsubmit attribute of the form to do whatever you want to before the form gets submitted. You can change action attribute also. You can also preventDefault as said here-
jQuery on submit preventDefault() does not works
You can give the elements a class, amountForTotal, and use a function to calc the total, which you can add to a button, or onchange event of an input.
function calcTotal( $elements ){
var total = 0;
$elements.each(function(){
// if the input has no value, add 0, if it has, add the value
total+= this.value.length===0 ? 0 : parseInt(this.value);
})
return total; // return the total
}
$elements = $('.amountForTotal'); // select them
// Bind an event to recalc the total
$elements.on('keyup', function(){
alert( calcTotal($elements) );
});
In this code I provided the selector as input. This is luxery, not needed, you can add that selector in the function, but this way it can be used more flexible. You can use the [name^=*] selector here, but its slower than a class, which you might notice in large documents.
Also, In my code I check if it has to no value to prevent errors. You can expand this to test if the input is actualy a number.

How to clear and replace the contents of an input field with the value of a button?

I think there is an easy solution however I have searched and cant seem to find he answer. I am trying set up several buttons that when pressed replace the the contents of an input field with the value of the button. I would prefer to control this with pure javascript rather than jquery if possible.
Also, if possible I would like the title of the button to be slightly different than the value it passes to the input field.
One way to do it
script:
function foo(id, el)
{
document.getElementById(id).value = el.innerHTML.replace(/test/, 'something');
}
(Obviously you'd want to do something more useful to the value than replacing test by something. But you can.)
html:
<input id="piet"/>
<button onclick="foo('piet',this)">test123</button>
<button onclick="foo('piet',this)">test234</button>
http://jsfiddle.net/sE2UV/
Assume this markup (an extra data attribute to avoid hardcoding the selector):
<input id="target" type="text">
<button value="potatoes" data-for="#target">Potato</button>
<button value="tomatoes" data-for="#target">Tomato</button>
You may use value attribute to store the data:
var buttons = document.querySelectorAll('button[data-for]');
for (var i = 0; i < buttons.length; i++) {
var targetId = buttons[i].dataset.for;
var target = document.querySelector(targetId);
buttons[i].addEventListener('click', function () {
target.value = this.value;
})
}
Demo: http://jsfiddle.net/dmu8N/
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function setText() {
document.getElementById("input1").value = "SOME TEXT";
}
</script>
</head>
<body>
<button type="button" onclick="setText()">Click me to set text!</button>
<input id="input1" type="text">
</body>
</html>
Full JSBin Example: http://jsbin.com/aZIyAzir/2/
Here's a jQuery solution for completeness.
<input type='text' id='target'></input>
<button>Merry</button>
<button>Christmas</button>
Then your jQuery:
$(function() {
var $target = $('#target');
$('button').on('click', function() {
$target.val($(this).html());
});
});

If length is less than 0 alert in javascript

Hi i have here a script for two text fields.
If the current length is 0 character... I want to alert that no characters left!
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<title></title>
</head>
<body>
<span id="limit">10</span><br/>
<input type="text" class="text_question_1"><br>
<input type="text" class="text_question_1">
</body>
<script type="text/javascript">
$(document).ready(function(){
//alert("test!!");
var combined_text_length = 0;
var limit = 10;
$("input.text_question_1").live('keyup', function (e){
current_length = 0;
$.each($("input.text_question_1"), function(index, value){
current_length += value.value.length
$(this).attr("#limit")
})
$("span#limit").html(limit - current_length)
})
})
</script>
</html>
I tried to put...
if (limit < 0){
alert("EXCEEDED!");
}
But not working.
current_length += value.value.length seems wrong. Use jQuery's own val() to retrieve the input field value as a string
Try
if (current_length > limit){
alert("EXCEEDED!");
}
As you are never modifying the limit variable itself, it can not get lower than zero.
Note that an alert is not particularly user-friendly. Lookup the jQuery plugin "lightBox".
Also, it seems you are trying to use a <input>s where a <textarea> might be more appropriate.

Categories

Resources