Jeremy
Jeremy

Reputation: 1835

Use javascript to calculate corresponding field

I am a beginner with jQuery and need to figure out how to automatically update one field when another has been changed. The code I have works for when the input field is changed, but I don't know how to find (and change) the corresponding field. Here's a jsFiddle

HTML:

<div>
    <div id='auto-calc'>
            <input></input>
    </div>
    <div>
        <p>(cm)</p>
    </div>
</div>
<div>
    <div id='auto-calc'>
            <input></input>
    </div>
    <div >
        <p>(inches)</p>
    </div>
</div>
<div>
    <div id='auto-calc'>
            <input></input>
    </div>
    <div>
        <p>(kg)</p>
    </div>
</div>
<div>
    <div id='auto-calc'>
            <input></input>
    </div>
    <div>
        <p>(lbs)</p>
    </div>
</div>

javascript:

$(document).ready(function() {
    $('#auto-calc input').change(function () {
        alert($(this));
    });
});

So with this, if (cm) changed, I would want to automatically change (inches), and vice versa. Same for (kg) <--> (lbs).

Any ideas? I know that I pretty close, I just can't figure out this last little part

this html will be repeated throughout my entire form. So there will be several cm/in and lbs/kg fields that will need to be corresponded to each other

Upvotes: 1

Views: 75

Answers (2)

matthias_h
matthias_h

Reputation: 11416

If you have multiple fields with the same unit, it's easier to uses classes for the input, like eg class="cm", and group corresponding fields together. An example for inch to cm in this adjusted Fiddle:

$(document).ready(function () {
  $('.cm').change(function () {
    $(".inch").val($(this).val() / 0.393701);
 });
});

If you would e.g. group corresponding fields in a container div with the class fieldgroup, this can be adjusted to

$(document).ready(function () {
  $('.cm').change(function () {
    $(this).closest(".fieldgroup").find(".inch").val($(this).val() / 0.393701);
 });
});

to change only the value of the corresponding inch input.

Upvotes: 1

Bob Brown
Bob Brown

Reputation: 1502

The ID attribute of an HTML element must be unique within a document. I suggest "in", "cm", "lbs", "kg". Put the ID on the input element so you can change its value directly.

Once you've done that, you'll need four 'change" functions, which is OK. When "in" changes, you can then set $(#kg").value and so on

Upvotes: 0

Related Questions