0

Following problem: I have some input fields of type range. jQuery mobile automatically transforms them into an input field with a slider aside. What I want to do is instant validation while typing. The validation script shall remove all non-digits. The function I use works on input field text but not for input type range.

This is my html:

<label for="my_range_input_field">label_text:</label>
<input data-type="range" type="range" name="my_range_input_field" id="my_range_input_field" value="10000" min="0" max="85000"  />

This is my jQuery validation function:

$(document).delegate('#my_range_input_field', 'input', function(e) {
    $(this).val($(this).val().replace(/[^\d]/g, ""));
});

The problem is, that this function deletes the whole input value and not just the non digits. I tried to debug and when using console.log to display the val I saw that it was always an empty string when not only digits were typed in the input field. I did some research and found the following: How to get the raw value an <input type="number"> field?

So there is something like a pre-validation and it seems that I can't retrieve the value I want because it's invalid and displays as empty string. Is there still a way to get that value?

Or is there at least something like a :invalid selector for input fields of type range to show the user a red background or something?

Community
  • 1
  • 1
user2718671
  • 2,866
  • 9
  • 49
  • 86

1 Answers1

1

You can use this general solution for preventing the input of alpha characters. Not my code but i cant find the link to credit the person who wrote the code.

Demo

https://jsfiddle.net/gv4xp4y7/

$(document).on("keydown", "input.ui-slider-input", function (e) {
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
    (e.keyCode == 65 && e.ctrlKey === true) || 
    (e.keyCode >= 35 && e.keyCode <= 40)) {
    return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
  e.preventDefault();
}});
Tasos
  • 5,321
  • 1
  • 15
  • 26
  • Thanks, but keydown functions doesn't work on touch devices. I found another solution. I transformed the input field to type text when focusin and back to range/number when focusout. – user2718671 Apr 13 '15 at 06:40
  • @user2718671 oh yeah that's a point i was testing on Desktop. however i just loaded the demo on my tablet (lg) and the keyboard is all numeric and i cant choose any characters except for (.). do you see the whole keyboard on your device? – Tasos Apr 13 '15 at 14:31
  • Well, the problem is that I want my validation script so that symbols from numpad like '#' etc. aren't allowed. So maybe my input field transformation is dirty but as long as it works I'm fine with it ;) Thx anyway! – user2718671 Apr 14 '15 at 08:29