Results 1 to 4 of 4

Thread: Comparing html5 data-set values produce unpredictable results

  1. #1
    Join Date
    Sep 2012

    Comparing html5 data-set values produce unpredictable results


    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.

    PHP Code:
    <!DOCTYPE html>
    input id="myField" type="number" value="10" data-max="25" data-min="3"> </input>

    script type="text/javascript">
    numberField document.getElementById("myField");
    numberField.addEventListener("change", function() { onFieldChange(numberField) });
    onFieldChange(obj) {
    obj.value obj.dataset.minobj.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
    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.

    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.

  2. #2
    Join Date
    Nov 2010
    those attributes are strings. try converting them to numbers:
            function onFieldChange(obj) { 
                if(Number(obj.value) < Number(obj.dataset.min)) obj.value = obj.dataset.min;

  3. #3
    Join Date
    Sep 2012
    Oh! That works, thank you!

  4. #4
    Join Date
    Jul 2008
    urbana, il
    or try the shorter-to-type and javascript-parser-unambiguous subtraction form:

    function onFieldChange(obj) {
    if( obj.value - obj.dataset.min < 0 ) obj.value = obj.dataset.min;
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center

Recent Articles