Search code examples
jquerykeyupcalculation

On keyup if value greater than X do something


I have two questions, using below code:

<h2>Daily KW usage</h2>
<p>Multiply daily usage by 91, divide 91 and divide 5</p>
<input name="box11" type="text" /><br />
<input name="box21" type="hidden" value="91" />
<input name="box31" type="hidden" value="5" /><br />
<input name="box41" class="box41" type="text" />

<div class="" id="showSearchDiv" style="display:none;margin-top:10px;height:450px;background-color:red;"></div>

$('input[name="box11"]').keyup(function() {
    var box11 = $('input[name="box11"]').val();
    var box21 = $('input[name="box21"]').val();
    var box31 = $('input[name="box31"]').val();
    $('input[name="box41"]').val(box11 * box21 / box21 / box31);
});

Firstly, once the calculation is done, before entering the answer into box41 as it currently does, how do I truncate/round-down the value to two decimal places?

Secondly, when the value is calculated and placed in box41, I am trying to work out how if this value is greater than 10 to show #showSearchDiv?

I understand the basics of show/hide etc but can't seem to work out how to tie it into the one operation with keyup.

Any help or pointers would be greatly appreciated.


Solution

  • Just added a few conditions in the same method. This will your answer.

    $('input[name="box11"]').keyup(function() {
        var box11 = $('input[name="box11"]').val();
        var box21 = $('input[name="box21"]').val();
        var box31 = $('input[name="box31"]').val();
        var result = box11 * box21 / box21 / box31;
        result = result.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0];
        
        if(result > 10){
          $('#showSearchDiv').show();
        } else {
          $('#showSearchDiv').hide();
        }
        $('input[name="box41"]').val(result);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h2>Daily KW usage</h2>
    <p>Multiply daily usage by 91, divide 91 and divide 5</p>
    <input name="box11" type="text" /><br />
    <input name="box21" type="hidden" value="91" />
    <input name="box31" type="hidden" value="5" /><br />
    <input name="box41" class="box41" type="text" />
    
    <div class="" id="showSearchDiv" style="display:none;margin-top:10px;height:450px;background-color:red;"></div>