Banana
Banana

Reputation: 57

Formating the value of a textarea input onload with jQuery

Background:

I have a webpage with numerous textarea input fields that will load numeric values from a database each time the page is loaded (via commented tags the webserver looks for on each page load, and then inserts values in their place). For example:

<input type="text" value="<!--#etc etc etc -->"/>

The problem I'm having is the data being pulled from the database is formatted with extra decimal spaces I don't need to display, and I'm not able to reformatted the data in the database.

After some searching I did find a very helpful jquery tutorial (found here: how-to-limit-two-decimal-digits-in-a-jquery-input-field.html) that does exactly what I need, but functions on the onkeyup event. Since my values are inserted into the pages and not by a user, I need the function to run automatically as soon as the page finishes loading. Is this possible?

Below is my most recent attempt using the html/script from the tutorial as a base, but so far I haven't had any luck after revising the keyup event to (what I believe are) onload events:

<input type="text" name="one" class="two-digits" value="123.45126"><br>
<input type="text" name="two" class="two-digits" value="654.31221">

// apply the two-digits behaviour to elements with 'two-digits' as their class
$(window).load(function() {
$('.two-digits').ready(function(){
    if($(this).val().indexOf('.')!=-1){         
        if($(this).val().split(".")[1].length > 2){                
            if( isNaN( parseFloat( this.value ) ) ) return;
            this.value = parseFloat(this.value).toFixed(2);
        }  
     }            
     return this; //for chaining
});
});

Any input would be greatly appreciated!

EDIT: I forgot to mention the webserver is an embedded qnx slinger server. So I don't have (and can't add) server side support for php, or any other common server side scripting languages.

Upvotes: 1

Views: 1011

Answers (2)

kfirba
kfirba

Reputation: 5441

If you are pulling the information from the database, and you are using PHP, you can use this function:

number_format($DB_VAL, 2);

that will round your number to be 2 numbers after the point.

EDIT:

Use the .each jquery function to loop through your textboxes and alter their values with your displayed function.

Upvotes: 0

Kierchon
Kierchon

Reputation: 2289

You need to use .each(). This will call the function on every item with the class

$('.two-digits').each(function(){
    if($(this).val().indexOf('.')!=-1){         
        if($(this).val().split(".")[1].length > 2){                
            if( isNaN( parseFloat( this.value ) ) ) return;
            this.value = parseFloat(this.value).toFixed(2);
        }  
     }            
     return this; //for chaining
});

http://jsfiddle.net/qFQCE/

Upvotes: 1

Related Questions