Search code examples
javascriptjquerynancustom-data-attributeparseint

parseInt returns NaN when it should be a number?


I have the following code:

$(function() {
    var $form = $("#pollAnswers"),
        $radioOptions = $form.find("input[type='radio']"),
        $existingDataWrapper = $(".web-app-item-data"),
        $webAppItemName = $existingDataWrapper.data("item-name"),
        $formButton = $form.find("button");
    
        $radioOptions.on("change",function(){
    
          $formButton.removeAttr("disabled");
    
          var chosenField = $(this).data("field"), 
              answer_1 = parseInt($existingDataWrapper.data("answer-1")),
              answer_2 = parseInt($existingDataWrapper.data("answer-2")),
              answer_3 = parseInt($existingDataWrapper.data("answer-3"));
            
            console.log("1 =" + answer_1);
            console.log("2 =" + answer_2);
            console.log("3 =" + answer_3);
            
            //Additional code not related to question
         });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="web-app-item-data" data-item-name="Test" data-answer-1="0"  data-answer-2="0"  data-answer-3="0"></div>

<form id="pollAnswers">
    <div class="answers">
        <input type="radio" name="radioChoice" data-field="CAT_Custom_2"> Answer 1<br>
        <input type="radio" name="radioChoice" data-field="CAT_Custom_4"> Answer 2<br>
        <input type="radio" name="radioChoice" data-field="CAT_Custom_6"> Answer 3<br>
    </div>
<button type="submit" disabled>Submit</button>
</form>

When you run the code you will see in your console that Answers 1, 2 and 3 all return NaN.

Update:

As Charlie H pointed out in a comment, if I remove parseInt it returns undefined.

I don't see the error in the code for why it isn't pulling the data attribute values from the div.

How do I solve this issue?


Solution

  • jQuery 2.1.3 does not appear to recognize data- attributes that contain a name-segment that consists only of numbers. For instance, these work:

    • data-answer as .data()["answer"]
    • data-foo as .data()["foo"]
    • data-foo-bar as .data()["fooBar"]

    These do not:

    • data-answer-1

    • data-foo-bar-3

    jQuery 3 appear to behave more as expected.