1

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

1
  • That code will only run once on page load, add event handlers if you want to update based on user input Commented Mar 2, 2015 at 21:44

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.