SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2007
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JQUERY loop through field values and change value

    Hi

    Using JQuery how do you loop through fields taking a value from each one and multiplying with a specific value.

  2. #2
    ********* Staff mattevans's Avatar
    Join Date
    Sep 2009
    Location
    Melbourne, Australia
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi david.j,

    I presume you have an array of data you are wanting to loop through?

    Code JavaScript:
    var yourNumbers = { 
        '1': '4', 
        '2': '8' 
    }; 
     
    $.each(yourNumbers, function(key, value) {
        // would alert 6 and 10, respectively.
        alert(parseInt(value) + 2);
    });

    ... or maybe looping through your forms input fields?

    Code JavaScript:
    $("#yourForm input[type=text]").each(function() {
        // your code here.
    });
    Matt Evans
    Sitepoint Developer
    tweet 2 me

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by david.j View Post
    Using JQuery how do you loop through fields taking a value from each one and multiplying with a specific value.
    From your topic summary, I presume that you are working with form inputs, such as:

    Code html4strict:
    <form id="calculate">
        <input name="value1">
        <input name="value2">
        <input name="value3">
        <input type="button" name="multiplyBy7">
    </form>

    When the button is clicked, you want to perform the calculation:


    Code javascript:
    $('input[name="multiplyBy7"]').click(function () {
        ...
    });

    Inside of that function, the this keyword will refer to the button itself, so you can use it to gain a reference to the form with this.form

    When the button is clicked you want to take each of those form inputs (I'm just using [name^="..." for all of the fields that start with the same word), and replace their value with the value multiplied by 7.

    Code javascript:
    $('input[name^="value"]', this.form).each(function () {
        this.value = this.value * 7;
    });
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •