Category : Tech Stuff

Get the values of an array of radio buttons – jQuery

Getting the value of a group of radio buttons is relatively straightforward, but what happens if you have more than one set?

I’ll start with a simple example of how to gather the data from a single set of radio buttons.

We’ll use this as our working example:

<div class="form-group">
  <div class="form-check form-check-inline">
    <input class="form-check-input checkMe" type="radio" name="amIChecked" value="yes">
    <label class="form-check-label" for="amIChecked">Yes</label>
  </div>
  <div class="form-check form-check-inline">
    <input class="form-check-input checkMe" type="radio" name="amIChecked" value="no">
    <label class="form-check-label" for="amIChecked">No</label>
  </div>
</div>

 

The jQuery to gather these fields would look something like this:

<script>
  jQuery(".checkMe").change(function(e) {
    e.preventDefault();
    const result = $("input[name='amIChecked']:checked").val();

    alert(result);

  })
</script>

In the above code, we are listening for a change event on the “checkMe” class.  At this point, we have asked the browser to provide the value of the input with the group name of “amIChecked”.

But what would happen if we were to produce a list, all ending in radio buttons?  If we adopted the above code, we would end up with only the result of the last set of radio buttons that the browser produced as it would keep re-attaching itself to the elements as they are rendered.  In this situation, we need to add something unique to each one.

I will assume at this point the list that your app is producing is being produced by a call to a database or similar.  If it isn’t and you just have a hard-coded list, this can still apply.

We need to take another approach to this to get this to fire correctly.  If you have been trying to do this with a similar method, then you will realise that applying the above method using a tweak of the above will produce hit and miss results.

The best way to approach this now is with a function.

Modified HTML:

<form id="{{ $thisRow->id }}">
  <div class="form-group"> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id="{{ $thisRow->id }}" name="amIChecked" onclick="clickedRadio('{{$rowID->id}}','yes')"> 
      <label class="form-check-label" for="amIChecked">Yes</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }}  name="amIChecked" onclick="clickedRadio('{{$rowID->id}}','no')"> 
      <label class="form-check-label" for="amIChecked">No</label> 
    </div> 
  </div>
</form>

I’m using the amazing Laravel framework in my project, so my ID is being produced in the Blade template using Laravels {{ }} syntax.  <?=$row->id;?> if you’re using vanilla PHP would be fine too.

You may notice I have also I have added <form> tags to each of the iterations in the loop.  This is because browsers will tend on only default the “checked” option (if you are using it) to the last iteration if everything has the same name value.  By adding <form> tags with a unique name, the browser treats all iterations as a single form.

Our function sends the row ID and the value to the jQuery for you to do with as you need.  With this in mind, there is no need to have the value=”” tags anymore, as they have been hardcoded in.

Now the modified jQuery:

<script> 
function clickedRadio(rowID, value)
    {
        alert(rowID + " : " + value);
     } 
</script>

With every click you should now get a row ID from your database (or whatever unique identifier you have chosen), and its value.  In this case, it will be yes or no, but it could be cats/dogs, on/off etc.

You aren’t limited to just two radio buttons using this method either.  This can be expanded to multiple values by just adding them in.

For example, this would be just as effective:

<form name="{{$rowID->id}}">
  <div class="form-group"> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','1')"> 
      <label class="form-check-label" for="userValue">Yes</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','2')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div>
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','3')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','4')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','5')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
  </div>
</form>

Have fun!

Share this post:
read more

Laravel Error: 1071 Specified key was too long

laravel-framework-help-and-guide

We’ve all been there.  We’ve installed a fresh new Laravel installation, come to do the migrations and hit the dreaded error message saying our email key was too long.

This is the message in question:

[IlluminateDatabaseQueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))

Thankfully, its really easy to fix.

Find the file: [your webroot]/app/Providers/AppServiceProvider.php

It will look like this from the default installation:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Simply change to look like this:

<?php


namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesSchema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

.. and all will be well 🙂

 

Share this post:
read more

Adding tabbed panels to Bootstrap – No jQuery

A great little piece of functionality built into Bootstrap is the ability to clear up some screen space using panels cascaded behind each other in tabs.  The best part is, it’s super easy to implement.

Here’s the code:

<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a href="#tab1" data-toggle="tab">Tab 1</a></li>
    <li><a href="#tab2" data-toggle="tab">Tab 2</a></li>
    <li><a href="#tab3" data-toggle="tab">Tab 3</a></li>
    <li><a href="#tab4" data-toggle="tab">Tab 4</a></li>
    <li><a href="#tab5" data-toggle="tab">Tab 5</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
    <div class="tab-pane active" id="tab1">
        <h1>Tab 1</h1>
    </div>
    <div class="tab-pane" id="tab2">
        <h1>Tab 2</h1>
    </div>
    <div class="tab-pane" id="tab3">
        <h1>Tab 3</h1>
    </div>
    <div class="tab-pane" id="tab4">
        <h1>Tab 4</h1>
    </div>
    <div class="tab-pane" id="tab5">
        <h1>Tab 5</h1>
    </div>
</div>

The above code will leave you something looking like this:

bootstrap-tab-loader

Feel free to use, copy and modify this code as you need to.

Share this post:
read more

Getting the ID of draggable and droppable elements – jQuery

jQuery’s drag and drop functionality is fantastic and adds excellent interactivity to your web application.  However, it can be a little confusing, so here are some straightforward examples that should get you off to a flying start when venturing into the world of drag and drop.

First, we need a few things to move around, so let’s create some:

<div id="div_01" class="draggable">Div 01</div>
<div id="div_02" class="draggable">Div 02</div>
<div id="div_03" class="draggable">Div 03</div>
<div id="div_04" class="draggable">Div 04</div>
<div id="div_05" class="draggable">Div 05</div>

You’ll need to get these in the context of your web page.

Next, we need somewhere to drop them:

<div id="dropzone_1" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>
<div id="dropzone_2" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>
<div id="dropzone_3" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>

I’ve used inline styles in the example above in case you are copying and pasting into a test HTML page of your own.  Inline styling isn’t great in a production environment; a separate style sheet is always better.  I’ve also assumed, that you have loaded the jQuery / jQuery UI version[s] of your choice onto the page by this point as well.

Making these elements draggable and droppable is easy.  Just add a function that covers both scenarios and then build upon them.

$(function () {
    $(".draggable").draggable();
    $(".dropzone").droppable();
});

At this point, you should be able to grab you divs and move them around the page.  They won’t do anything aside from move around the page, but it’s quite a novelty the first time it happens successfully!

It’s at this point the language used by jQuery can be a little bit confusing.  “Draggable” is obvious; it is something that can be dragged around the screen, its when you get to “droppable” that people sometimes run into confusion.  “Droppable” suggests you are dealing with something that once you start dragging around, is then available to be dropped, however, this isn’t the case.  “Droppable” by jQuery’s definition is the area that you drop a draggable.  The draggable itself, contains the drop event, whereas the droppable is just a static place your draggable gets dropped.

Confused yet? Don’t be; it’s effortless when you see it broken down.

Doing something with my draggable and droppable.

Take a look at this extended version of the code snippet above.  What you see below is taken directly from one of my live projects, so will need to be customised to suit your project:

$(function () {
    $(".draggable").draggable(
        {
            start:
                function (event, ui) {
                    $(this).css("z-index", 10);
                }
        }
    );
    $(".dropzone").droppable({
        drop: function (event, ui) {

            const dropZoneID = $(this).attr('id');
            const droppedItemID = ui.draggable.attr("id");

            /* 
             Do something with your newly gathered information
             */
        }
    });
});

So what is going on in the code above?  Let’s start with the draggable.  There are various events associated with the draggable.  Notably, these are start, stop and drag.  In the example above I’ve used the start event to bring the item, I’m dragging to a z-index of 10.  With my Bootstrap projects, I’ve found this handy to ensure the thing I’m dragging around remains at the top.  If I don’t set this index with Bootstrap, the draggable can end up going behind some of the other elements.

You can find a full reference to jQuery draggable here.

Lovely, but the exciting part comes when you drop these draggable.

The two critical pieces of information you need when dealing with draggable items and dropzones [and this may seem obvious] are, what you’ve dropped and where you’ve dropped it.  This is achieved using the “drop” event inside the droppable.  Here, I have created two constants [variables are also fine] that will gather this information.

A great way to visualise this if you are starting out with these is to add a test div, so you can see what’s happening.

Create a div, like this:

<div id="testDropDiv"></div>

Then in your code, add the following:

$(".dropzone").droppable({
        drop: function (event, ui) {

            const dropZoneID = $(this).attr('id');
            const droppedItemID = ui.draggable.attr("id");

            $("#testDropDiv).empty()
                     .append("I've just dropped div with ID: " + droppedItemID + " Onto: " + dropZoneID);

        }
    });

Which should then update each time you drop one of your draggable onto a dropzone.

The reference for jQuery droppable is available here.

I hope that gives a little bit of an insight into jQuery’s draggable and droppable.  This short introduction has only just scratched the surface of what is achievable.  I would recommend you have a look at the jQuery UI website to see some more examples.

Share this post:
read more

PHP – Validate a UK postcode

php-banner

Returns a true/false against a UK postcode, as well as attempting to format it correctly.

There are a million versions of this code on the internet, but being true to my FluffedVision roots and treating this as my notebook, rather than a traditional blog, I’m noting this snippet down here.

function isValidPostcode($originalPostcode)
{
    $alpha1 = "[abcdefghijklmnoprstuwyz]";
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";
    $alpha3 = "[abcdefghjkpmnrstuvwxy]";
    $alpha4 = "[abehmnprvwxy]";
    $alpha5 = "[abdefghjlnpqrstuwxyz]";

    $pcexp[0] = '/^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/';
    $pcexp[1] = '/^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/';
    $pcexp[2] = '/^('.$alpha1.'{1}'.$alpha2.'{1}[0-9]{1}'.$alpha4.')([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/';
    $pcexp[3] = '/^(gir)([[:space:]]{0,})(0aa)$/';
    $pcexp[4] = '/^(bfpo)([[:space:]]{0,})([0-9]{1,4})$/';
    $pcexp[5] = '/^(bfpo)([[:space:]]{0,})(c/o([[:space:]]{0,})[0-9]{1,3})$/';
    $pcexp[6] = '/^([a-z]{4})([[:space:]]{0,})(1zz)$/';
    $pcexp[7] = '/^ai-2640$/';
    $postcode = strtolower($originalPostcode);

    $valid = FALSE;

    foreach ($pcexp as $regexp)
    {
        if (preg_match($regexp, $postcode, $matches))
        {
            $postcode = strtoupper ($matches[1] . ' ' . $matches [3]);
            $postcode = preg_replace ('/C/O([[:space:]]{0,})/', 'c/o ', $postcode);
            preg_match($pcexp[7], strtolower($originalPostcode), $matches) AND $postcode = 'AI-2640';
            $valid = TRUE;
            break;
        }
    }

    return $valid ? $postcode : FALSE;
}

Usage:

if(isValidPostcode("thePostcodeToCheck"))
{
  // postcode is valid
}
else
{
  // postcode is not valid
}

 

Share this post:
read more

Create a character countdown for text inputs and textarea’s using jQuery

I think it may have been Twitter that first pioneered the use of the text character countdown years ago.  I could be wrong, maybe they just popularised it, but either way, it is a convenient way of keeping user inputs to a length that is acceptable to your site.

I’m not sure that this is the place to mention it, but I do still find myself writing shorter tweets, despite the limit raise a while ago.

There are going to be three main parts to this:

  • Create an HTML form that needs the input characters kept in check.
  • Write some jQuery code to keep an eye on what is happening when the user’s types.
  • Style a little blank <span> underneath the input to show the user how they are getting on.

For those of you that read regularly, you will know I am a big Bootstrap fan (hark the Twitter reference again), so the form has some Bootstrap elements to it.  This form will work just as well without the BS references.

Create the input:

<label for="myInput"><strong>My Limited Input:</strong></label>
<input class="form-control" type="text" id="myInput" maxlength="50">
<span id="showCountdown" class=limits"></span>

I’ve used the HTML “maxlength” in the above snippet so that the browser automatically restricts any more inputs at that point.  The HTML “maxlength” has nothing to do with the character countdown.  “maxlength” is universally accepted on most browsers except for the ancient, so you shouldn’t run into many [if any] compatibility problems.

Just for curiosities sake, the default value for maxlength is 524288.

Next, we need to add some jQuery to do the counting and append the <span> underneath the input:

$('#myInput').on("keyup change", function ()) {

  const max = 50;
  const len = $(this).val().length;

  if (len >= max) {
    $('#showCountdown').text("No more room ...");
  } else {

    const char = max - len;
    $('#showCountdown').text(char + ' characters remaining');
  }
});

So what’s happening here?

The browser is looking for either a keyup event or a change event occurring in the input.  Change is handy because, in the majority of cases, the will also catch the user if they try and paste something into the box.  When the event is detected, it counts the length of the string inside the input.  It then compares it to the max variable we’ve included and deducts one from the other.

After evaluating whether the length of the input is smaller (by x number) or equal to the max value, it adds an appropriate message into the empty span underneath the box.

Now a little styling:

<style>
#showCountdown {
  font-size: 12px;
  color: #3399ff
}
</style>

You can style this in any way you wish.

Below is an example of this text input in action on a site I’m working on at the moment,  Although I think I used dodgerblue as the colour:

 

 

Share this post:
read more

How to show your latest blog posts on a non-WordPress page

wordpress-blog-header-fluffed-vision

Quite often on a website, there is a need to show your WordPress blog posts outside of the WordPress installation.  You may already have an HTML / PHP site, and you have decided to add a blog page, but want to show some of the posts on the front page (for example).  Luckily, WordPress makes this process as easy as adding a few lines of code to your pages.

You will need a little bit of familiarity with PHP, but realistically, anybody should be able to do it.

There are two things to do:

First, you need to tell your non-Wordpress page that you are going to be extracting information about your posts. So, at the top of the page add the following:

<?php 
  define('WP_USE_THEMES', false);
  require('/wp-load.php');
  query_posts('showposts=4');
?>

Let’s break this down a bit.

The first line tells WordPress that it won’t be needing to use any of its themes.  We are adding the posts to a page that we will assume is already using a stylesheet of its own, so we need the extracted WordPress information to blend in accordingly.

The “require” line will need to be relative to your wp-load.php, so if you have added your blog in the default WordPress directory, this line may end up as:

// If it's in a directory called "wordpress"

require('wordpress/wp-load.php');

// If you need to backtrack to server root to get to you sub-folder

require('../wordpress/wp-load.php');

The exact structure of this line is individual web server and code dependent so will need to be adjusted to suit your exact requirements.

The second line is pretty self-explanatory, it is telling the page to use the WordPress loader.  The loader is required whenever you call anything from WordPress, be it posts, pages, categories etc.

The third line is what we want to extract from the WordPress database.  In this case, we are pulling the lastest four posts.

Following this, we will need to display the posts on the page.  We do this using the standard WordPress API in the form of WordPress hooks.

So:

<?php while (have_posts()): the_post(); ?>

  <h4><?php the_title(); ?></h4>

  <?php the_excerpt(); ?>

  <p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>

<?php endwhile; ?>

 

That’s it!

The first and last lines tell the page to show posts if there are posts available.  From there, it is just a list of standard WordPress hooks, which on the whole of quite explanatory.  While we are looping through four posts, for each of them, show the post’s title, the excerpt from the post – which can be adjusted in the WordPress admin panel – then add a link to read more.  This link will take the user to the main blog page.

Want to show the full post and not an excerpt from it? No problem.  Just replace “the_excerpt” with “the_content”.

Want to add the posts featured image as well?  No problem, include:

<?php
  if ( has_post_thumbnail() ) {
      the_post_thumbnail();
  }
?>

Here are some working examples:

An example snippet that would show the title of the post, along with the featured image and an extract of the content:

<?php while (have_posts()): the_post(); ?>
 <h4><?php the_title(); ?></h4>
 <p>
  <?php
    if ( has_post_thumbnail() ) {
      the_post_thumbnail();
    }
  ?>
 </p>
 <?php the_excerpt(); ?>
 <p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>
<?php endwhile; ?>

An example snippet that will show the title, full post, but no image:

<?php while (have_posts()): the_post(); ?>
 <h4><?php the_title(); ?></h4>
 <?php the_content(); ?>
 <p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>
<?php endwhile; ?>

If anybody would like to add some more code examples to the comments, I’ll be glad to see them and we’ll get them added to the main post to build up a little library of useful snippets.

 

 

 

Share this post:
read more

Getting the value or text of an HTML attribute using jQuery

Grabbing attributes to use in your JavaScript is often handy.  HTML attributes can be used to send various options to your script or attributes used for multiple switches to control different elements of what you are doing.

You can use HTML attributes on their own, or grab them from specific elements with this.

If you are using a standalone element, such as:

<button class="btn btn-outline-success btn-sm buyButton" value="profile" customTitle="Profile Upgrade">BUY</button>

You can use a specific selector:

const itemTitle = $('.buyButton').attr('customTitle');

If you are using multiple selectors, then you can grab the values from the button you want, when using onClick, for example, in a similar way.

So if you have:

<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="profile" customTitle="Profile Upgrade">BUY</button>
</div>
<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="listing" customTitle="Listing Upgrade">BUY</button>
</div>
<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="highlight" customTitle="Highlight Listing">BUY</button>
</div>

(I’ve made some of these up, and some of the bits are unnecessary, like the DIV’s, they are just in the project I’m working on)

So if you want to get the customTitle attribute to use in your logic somewhere, use:

$(".buyButton").on('click', function(e) {
    e.preventDefault();
    const customTitle = $(this).attr('customTitle');
})

 

Share this post:
read more

Get the value of selected radio buttons – jQuery

If you need to get the value of a selected radio button dynamically, to send for processing via an AJAX call for example, then the following is a great way to achieve this.

The general methodology is to give all of the radio options a generic class that can be used to trigger the onchange event. Then, grab the value of the radio button that has been selected and use it in your processing script.

In the below example, we use the “class” to define the group, the “name” to define what we are selecting, and the “value” to determine what is then sent to the processing script.

The radio buttons:

<div class="row">
  <div class="col-sm-6">
    Option 1
  </div>
  <div class="col-sm-6">
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option1" value="show" checked>Show
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option1" value="hide">Hide
      </label>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-sm-6">
    Option 2
  </div>
  <div class="col-sm-6">
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option2" value="show" checked>Show
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option2" value="hide">Hide
      </label>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-sm-6">
    Option 3
  </div>
  <div class="col-sm-6">
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option3" value="show" checked>Show
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option3" value="hide">Hide
      </label>
    </div>
  </div>
</div>

There’s a lot of Bootstrap 4 formatting in there as well, as this was taken from one of my live projects.  I have also used the values “show” and “hide”, as these are project specific, but you could add any values you require in here.

Then some JavaScript to do the actual work:

$(".viewChange").on("change", function(e){

    e.preventDefault();

    const option1status = $("input[name='option1']:checked").val();
    const option2status = $("input[name='option2']:checked").val();
    const option3status = $("input[name='option3']:checked").val();

    /*
    Do something with your now created constants
    */

});

 

This will produce the outputs you need to then do processing as you require.

Share this post:
read more

Ensure only a UK decimal value is added to a textbox – JavaScript

If you are adding a price, or a value to a textbox input, you may need to sanitise it.  This script will make sure that nothing is allowed in the box except for a decimal point and numeric values.  It will also ensure that there is only two numbers after the decimal place and that there can only be one decmial place.

$('#someTextInput').keypress(function(event) {
        var $this = $(this);
        if ((event.which !== 46 || $this.val().indexOf('.') !== -1) &&
            ((event.which < 48 || event.which > 57) &&
                (event.which !== 0 && event.which !== 8))) {
            event.preventDefault();
        }

        var text = $(this).val();
        if ((event.which === 46) && (text.indexOf('.') === -1)) {
            setTimeout(function() {
                if ($this.val().substring($this.val().indexOf('.')).length > 3) {
                    $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
                }
            }, 1);
        }

        if ((text.indexOf('.') !== -1) &&
            (text.substring(text.indexOf('.')).length > 2) &&
            (event.which !== 0 && event.which !== 8) &&
            ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
        }
    });

    $('#someTextInput').bind("paste", function(e) {
        var text = e.originalEvent.clipboardData.getData('Text');
        if ($.isNumeric(text)) {
            if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
                e.preventDefault();
                $(this).val(text.substring(0, text.indexOf('.') + 3));
            }
        }
        else {
            e.preventDefault();
        }
    });

 

Share this post:
read more
1 2 3 4