2

I am having a input type text.

<input type="text" class="checkForDot" />

What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.

my jquery code is:

 $(".checkForDot").on("keyup", function (event) {
      CheckForDot($(this).val());
   });

function CheckForDot(value) {
     if (value != null || value != '') {
         var str = value.toString();
         if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
             console.log("ok");
               }
            }
        }

It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?

If any other approach better than this please tell.

DevProf
  • 564
  • 7
  • 19
  • 2
    Possible duplicate of [JavaScript Regex for positive numbers with one dot and 2 decimal](https://stackoverflow.com/questions/42549833/javascript-regex-for-positive-numbers-with-one-dot-and-2-decimal) – Matías Fidemraizer Jun 06 '18 at 07:34

2 Answers2

5

$(document).ready(function() {
var original='';
 $('.checkForDot').on('input', function() {
   if ($(this).val().replace(/[^.]/g, "").length > 1){
    $(this).val(original); 
  }else{
   original = $(this).val();
  }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='checkForDot' />

Try to use this regex to find how many dots you got in string.

Wils
  • 1,149
  • 6
  • 22
0

If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.

A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.

The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.

let lastValidInputValue;
let selectedDot = false;


const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;
};


const onInput = (e) => {
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
 }
<input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">

You can find very detailed comments and extra bits in this Codepen

Samuel Charpentier
  • 429
  • 1
  • 4
  • 21