jquery x-editable numeric input

Chris Ian picture Chris Ian · Aug 2, 2013 · Viewed 8k times · Source

In x-editable library. How to have a numeric input? That does not allow any letter in the input box.

I have tried this code

<a class="items" data-name="itemqty" data-title="Enter Item Quantity" data-type="text" href="#" id="itemqty" onkeypress="return isNumberKey(event)"></a>

<script>
    function isNumberKey(evt) {
      var charCode = (evt.which) ? evt.which : event.keyCode;
      if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
          return false;
      } else {
          return true;
      }      
    }
</script>

but it does not work. If I used a normal input text it works but in x-editable it does not work. Any ideas?

Answer

Philipp P picture Philipp P · Aug 26, 2014

The following solution works for me:

    $('.editable').editable({
        type: 'text', 
        validate: function(value) {
            if ($.isNumeric(value) == '') {
                return 'Only numbers are allowed';
            }
        }
    });

It's important to return an error string (e.g. 'Only numbers are allowed') because otherwise x-editable doesn't recognice that the validation has failed.