Javascript Math Functions

17,739

Solution 1

You can act on each individual input using an each()(docs) loop.

Click here to test a working example. (jsFiddle)

$('a.square').click(function() {
    $('#myform :text').each(function() {
        this.value *= this.value;
    });
});

$('a.square_root').click(function() {
    $('#myform :text').each(function() {
        this.value = Math.sqrt(this.value);
    });
});

When either link is clicked, it finds all the text inputs in myform and iterates over them.

Inside the each function, this refers to the current input element.

Solution 2

JQuery doesn't need to support math functions as it is an addon library for Javascript, you can still use Javascript in your JQuery code, so you can still use all the native math functions.

Examples:

Addition

var x = 1;
var y = 2;
var lol = x+y;
alert(lol);

Subtraction

var x = 10;
var y = 1;
var lol = x-y;
alert(lol);

Edit: Now we understand your question a little better...

<input type="text" id="field1" value="16" />
<input type="text" id="field2" value="25" />
<input type="text" id="field3" value="36" />

var field1Value = document.getElementById("field1").value;
var field2Value = document.getElementById("field2").value;
var field3Value = document.getElementById("field3").value;

alert(Math.sqrt(field1Value ));
alert(Math.PI * field2Value);
alert(Math.sin(field3Value));

Solution 3

It would be quite useful if jQuery had a reduce() function.

When dealing with lists of data, most functional languages, and indeed most traditional languages these days, have methods that perform a repetitive function over the entire list, taking each element in turn and applying a function to it.

The simplest of these is map, which jQuery implements for you. This takes a list and applies a function to each element and returns the list of results, one result per entry in the list. eg. [1,2,3] -> (map x2) -> [2,4,6].

Sometimes you want a total or collective result from a list, rather than a list of individual mappings. This is where the reduce (or fold) operation comes in. Unfortunately jQuery does not have this method available as standard, so below is a plugin for it. A reduce function takes an accumulator value and the value of the current element, and returns the modified accumulator, which will be passed on to the next call. eg. [1,2,3,4] -> (reduce + [initial:0]) -> 10 = ( ( ( (0 + 1) + 2 ) + 3 ) + 4 ) or ([1,2,3,4] -> (reduce * [initial:1]) -> 24 = ( ( ( (1 * 1) * 2 ) * 3 ) * 4 ).

(function($) {
    $.reduce = function(arr, callback, initial) {
        var accumulator = initial || 0;

        $.each(arr, function(index, value) {
            accumulator = callback(accumulator, value, index);
        });

        return accumulator;
    }
})(jQuery);

Then you can use it like this to get a sum of squares:

var answer = $.reduce($('input:text'), function(acc, elem) {
    var cVal = $(elem).val();
    return acc + cVal * cVal;
}, 0);

Solution 4

i was looking for a solution too , and i saw a lot of questions here that doesn't work (even this one) in case someone wondering like me , here is my working solutiuon :

$("#apport").keyup( 
function(){
var apport = parseFloat($("#apport").val());
var montant = parseFloat($("#montant-financer").val());
var moinmontant = parseFloat(montant) - parseFloat(apport);     
$("#montant-financer").val(moinmontant);    
}
);

All the id's selector are input

Solution 5

JavaScript is the programming language, not jQuery, which is a library for web application programming written in JavaScript. To effectively use jQuery, you need to know JavaScript.

It is, however, possible to use jQuery's functionality to easily work with multiple textboxes at once:

// Set each single-line textbox's value to the square
// of its numeric value, if its value is in fact a number.
$('input:text').each(function() {
    var num = +this.value;
    if(!isNaN(num)) {
        this.value = num * num;    // or Math.pow(num, 2)
    }
});
Share:
17,739
Eray
Author by

Eray

Updated on August 26, 2022

Comments

  • Eray
    Eray over 1 year

    How can I use these JavaScript math functions ?

    For example, I want to compute the square of all <input> values in a form, without submiting the form.

    Can you give a little example? Thank you.

    • casablanca
      casablanca over 13 years
      Example of what? You need to be more specific in order to get an answer here.
    • polarblau
      polarblau over 13 years
      It doesn't make any difference if you're using jQuery or not. The Math functions work as usual.
    • Andy E
      Andy E over 13 years
      Please don't use w3schools as a resource for learning JavaScript (or anything else, for that matter). w3fools.com
    • Eray
      Eray over 13 years
      You misunderstood me (or i can't explain myself) . I don't know javascript to much. So i need a small example which return square of all <input>'s , for example.
    • Tom Gullen
      Tom Gullen over 13 years
      @Eray consider opening a new question but be more descriptive, and maybe show us the code you already have
    • Eray
      Eray over 13 years
      @Tom, They misunderstood me and comments are really funny :) (For example BoltClock's comment "How is it possible to know jQuery without knowing JavaScript?") . Maybe i can't explain. Question edited. You can check again but question is closed.
    • Tom Gullen
      Tom Gullen over 13 years
      All you need to do, is get all the values in the fields, like: var field1 = document.getElementById("field1").value; etc etc, then do whatever you want with the result, IE alert(Math.sqrt(field1)); Avoid JQuery for simple things, it overcomplicates it, I have no idea why people use it for such trivial tasks.
    • Eray
      Eray over 13 years
      @Tom, thank Tom i'm trying this now. Can i get all <input> with a code ? (like an array) . Because there is a lot of <input> .jsfiddle.net/z4GvJ/1
    • Crescent Fresh
      Crescent Fresh over 13 years
      @Eray: what was your problem with Shog9's edit? What did you think he did not understand?
    • Eray
      Eray over 13 years
      My question isn't about JQUERY. When i say JQUERY , people thinks "I know javascript but i don't know using (coding) JQUERY" . But actually, I don't know javascript (and JQUERY too ) . My questions edited about 4 times.
    • goat
      goat over 13 years
      I agree, jQuery is really the best, it solves all kinds of browser problems and is good, as well.
    • George Claghorn
      George Claghorn over 13 years
      From the StackOverflow FAQ: "Like Wikipedia, this site is collaboratively edited, and all edits are tracked. If you are not comfortable with the idea of your questions and answers being edited by other trusted users, this may not be the site for you."
  • BoltClock
    BoltClock over 13 years
    @Eray Alakese: How is it possible to know jQuery without knowing JavaScript?
  • casablanca
    casablanca over 13 years
    @BoltClock: It is unfortunate that what you just mentioned has become the norm rather than the exception.
  • Eray
    Eray over 13 years
    @BoltClock, :D . You misunderstood me. Question edited. You can check. Thanks.
  • Šime Vidas
    Šime Vidas over 13 years
    Or: $('#myform :text').val(function(i,v) { return v*v; });
  • Raynos
    Raynos over 13 years
    You might want to explain what reduce means. If he's having trouble with using the Math library he might not understand what a reduce does.
  • Raynos
    Raynos over 13 years
    Another point is that you can check for array.reduce which is implemented in firefox & chrome. Native code always runs better
  • Orbling
    Orbling over 13 years
    @Raynos: Very true, I tend to ignore the existence of functions that do not exist (at least in some format) in all browsers. But the implementation could use the underlying function where available if handled properly.