user557419
user557419

Reputation:

Append text to element value

I multiply the integer value of 3 textboxes and display the result in a 4th textbox.

Before the value is displayed I want to check if the value contains any decimals, like 99.95. If it doesn't then the script shall append .00 to the value (99.00).

<script type="text/javascript">
$(document).ready(function () { 
    $("input:text").each(function(){ 
        $(this).blur(function () { 
            var txt1 = $('#<%=TextBox1.ClientID %>').val();
            var txt2 = $('#<%=TextBox2.ClientID %>').val();
            var txt3 = $('#<%=TextBox3.ClientID %>').val();
            var txt4 = $('#<%=TextBox4.ClientID %>'); // To display the value.
            var value = parseFloat(txt1) + parseFloat(txt2) + parseFloat(txt3);
            txt4.val(value);
        });
    });
});
</script>

I have tried various ways like:

if($(value).has('.').length === 0){ value.append('.00'); }
$(value).not('.').append('.00');

etc.

None of which has worked so far. I have tried any if-statement I can think of available with jQuery.

Upvotes: 0

Views: 509

Answers (2)

Brad Christie
Brad Christie

Reputation: 101614

txt4.val(value.toFixed(2));

Little shorter, less headache.

Upvotes: 5

niksvp
niksvp

Reputation: 5563

Use this

JavaScript built-in methods toFixed and toPrecision

Upvotes: 1

Related Questions