How can I get values of inputs that have the same class using JQuery each?

放肆的年华 提交于 2019-12-02 20:57:43

问题


This should be easy, but I can't seem to get it right.

var totalHours = 0;
this.$(".timesheet-daily-input").each( function () {
    var inputValue = $(this).text();
    var hours = parseInt(inputValue);
    totalHours += (hours == null) ? 0 : hours;
});

I've tried $(this).val() and $(this).html() as well, but can't get the values out of the input fields.

Edit: Apologies, I knew I was forgetting to mention something. The "this." at the start of the each loop is because I am using backbone's models and collections. The first "this." refers to the specific model in question. It loops through the proper number of times, I just can't get the value.


回答1:


Get rid of the this. before $(".timesheet-daily-input") and use $(this).val() to get the value of the inputs.




回答2:


var inputValue = $(this).val();



回答3:


It's hard to tell without more code but change

var inputValue = $(this).text();
var hours = parseInt(inputValue);
totalHours += (hours == null) ? 0 : hours;

to

var inputValue = $(this).val(); // use val
var hours = parseInt(inputValue, 10); // use 10 as radix
totalHours += isNaN(hours) ? 0 : hours; // compare to NaN instead of null

Note that parseInt("09") is 0 and that the result of parseInt cannot be null.




回答4:


Couldn't find an exact solution, but changed my approach by selecting the parent div, and looping through it's child elements.

var totalHours = 0;
this.$("#timesheet-daily-entry-fields-container").children().each(function () {
    var inputValue = $(this).val();
    var hours = parseInt(inputValue);
    totalHours += isNaN(hours) ? 0 : hours;
});


来源:https://stackoverflow.com/questions/12941215/how-can-i-get-values-of-inputs-that-have-the-same-class-using-jquery-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!