Powered by Blogger.

Jquery price input only number and point


This one is a simple jquery price input, only number and point accepted. No need to add any other plugin just simple codes. If you want you may do it with Javascript. Following codes tested under WordPress 3.8.1
The code will only allow one point infield, and the first character must be a number, and the last character won’t be the point

Step 1: Add class “wpprogramming-price-only” to your input text field.

<input type="text" name="price" id="price_id" value="" class="wpprogramming-price-only"/>


Step 2: Add the following codes to your js file.

jQuery(document).ready( function($){
    $(".wpprogramming-price-only").keyup( function(){
        //only number and .
        this.value = this.value.replace(/[^0-9\.]/g, '');
        //first must be number
        this.value = this.value.replace(/^\./g, '');
        //.. is not allowed
        this.value = this.value.replace(/\.{2,}/g, '.');
        //only one . allowed
        this.value = this.value.replace('.','$#$').replace(/\./g, '').replace('$#$', '.'); 
    });
    $(".wpprogramming-price-only").focusout( function(){
        //if the last one is . then remove it number and .
        this.value = this.value.replace(/\.$/g, ''); 
    });
});

In WordPress, if you don’t have a js file then you may take the following ways:

Step 1: Open the function.php file which sitting in your active theme folder and add the following:

add_action('wp_footer', 'wpprogramming_price_input');
function wpprogramming_price_input(){
    wp_enqueue_script( 'jquery' );
    ?>
    <script type="text/javascript">
    jQuery(document).ready( function($){
        $(".wpprogramming-price-only").keyup( function(){
            //only number and .
            this.value = this.value.replace(/[^0-9\.]/g, '');
            //first must be number
            this.value = this.value.replace(/^\./g, '');
            //.. is not allowed
            this.value = this.value.replace(/\.{2,}/g, '.');
            //only one . allowed
            this.value = this.value.replace('.','$#$').replace(/\./g, '').replace('$#$', '.'); 
        });
        $(".wpprogramming-price-only").focusout( function(){
            //if the last one is . then remove it number and .
            this.value = this.value.replace(/\.$/g, ''); 
        });
    });
    </script>
    <?php
}

Step 2: Just copy the above codes to your plugin file.

No comments