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.

Hi david.j,

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

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?

$("#yourForm input[type=text]").each(function() {
    // your code here.
});

From your topic summary, I presume that you are working with form inputs, such as:


<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:


$('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.


$('input[name^="value"]', this.form).each(function () {
    this.value = this.value * 7;
});