user3806523
user3806523

Reputation: 59

Updating a variable when input changes in jquery

I'm trying to create a simple px to em converter that automatically calculates the values when one of the input fields is changed. I've got the code to calculate the values but it won't update when a value is changed.

Heres the HTML

<body>
    <h1>PX to EM converter</h1>

    <div id="base">
        <h2>Enter a base pixel size</h2>
        <input id="baseSize" value="16">
        <p>px</p>
    </div>

    <div id="px">
        <input id="pxInput" value="16">
        <p>px</p>
        <div id="emOutput2"></div>
    </div>
    <p>em</p>

    <div id="Em">
        <input id="emInput" value="1">
        <p>em</p>
        <div id="pxOutput2">
        </div>
        <p>px</p>
    </div>
</body>

And the js

$(document).ready(function() {
    var baseSize2 = $('#baseSize').val();
    var pxInput = $('#pxInput').val();
    var emInput = $('#emInput').val();
    var emOutput = function() {
        return pxInput / baseSize2;
    };
    var pxOutput = function() {
        return emInput * baseSize2;
    };

    $('#baseSize').attr('value', baseSize2);
    $('#pxInput').attr('value', pxInput);
    $('#emInput').attr('value', emInput);
    $('#pxOutput2').html(pxOutput);
    $('#emOutput2').html(emOutput);
});

Any help would be most appreciated

Upvotes: 1

Views: 6779

Answers (2)

Matthew North
Matthew North

Reputation: 555

I've created a JSFiddle here for you.

I've set it in the keyup event:

$("#pxInput").keyup(function(){
         var emOutput = function (){ return $('#pxInput').val()/$('#baseSize').val();};
         $('#emOutput2').html(emOutput);
    });
    $("#emInput").keyup(function(){
         var pxOutput = function (){ return $('#emInput').val()/$('#baseSize').val();};
         $('#pxOutput2').html(pxOutput);
    });

Upvotes: 1

Matt
Matt

Reputation: 1580

At the moment, you've got nothing to listen for changes on the input boxes. jQuery's change listener is very easy.

$('#baseSize').change(function() {
   // Code in here will run when the baseSize input is changed
   // Note that this must be inside your jQuery ready/onload function.
   // Note that this will **not** work with dynamically added elements
});

Also, when updating an input use jQuery's value function instead of accessing the attribute.

$('#baseSize').attr('value', baseSize2);
// Should be
$('#baseSize').val(baseSize2);

Upvotes: 3

Related Questions