Hello!
I have multiple text input fields that accept numbers, and I want to clamp the value within a set range. I have working code to parse the input to make sure it's a valid number, but the problem I'm having is with the code to clamp the resulting number.
When I compare the value with the custom data attributes, I get strange results. For example, if I enter "2", it changes to 3 as expected. Any single digit number will work correctly, but "10" will be considered less than 3 here. After some testing, it looks like only the first number of the value is being considered with the if statements. 3456 will remain in the input, as it should, but 23456 will get changed because it starts with 2.PHP Code:<!DOCTYPE html>
<body>
<input id="myField" type="number" value="10" data-max="25" data-min="3"> </input>
<script type="text/javascript">
var numberField = document.getElementById("myField");
numberField.addEventListener("change", function() { onFieldChange(numberField) });
function onFieldChange(obj) {
if(obj.value < obj.dataset.min) obj.value = obj.dataset.min; //doesn't work right
//if(obj.value < obj.getAttribute("data-min")) obj.value = obj.getAttribute("data-min"); //same deal
//if(obj.value < 3) obj.value = 3; //this works as expected
}
</script>
</body>
If I use javascript variables in place of custom attributes, everything seems to be ok, except my code is longer. I'd rather use the custom attributes if I can.


Reply With Quote
Bookmarks