Float validation in text field using jQuery

We often need to allow only float values in some fields like for tax, money, price etc. To achieve this we can use this code. 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script>
//only decimal
$('.d3').keypress(function(e) {
if(e.which == 46 && $(this).val().indexOf('.') != -1) {
e.preventDefault();
} 
if (e.which == 8 || e.which == 46) {
return true;
} else if ( e.which < 48 || e.which > 57) {
e.preventDefault();
}
});
//handle paste
$('.d3').on('paste input propertychange', function (e) {
$(this).val( $(this).val().replace(/[^0-9.]/g, '') );
})
</script>

It works well for copy paste also.  If  you try to copy `Section 1.2` in textbox it copy only 1.2.

Demo




Post a Comment