jQuery - 根据属性获取所选选项后下拉列表中下一个选项的总值

jQuery - Get Total value of the next options in a dropdown after the selected one based on attribute

HTML输出

<option data-task-hours="100" value="1"> - Parent Task</option>
<option data-task-hours="50" value="2"> -  - Child task</option>
<option data-task-hours="50" value="3"> -  - Child task</option>

jQuery 获取下一个选项值的代码:

$('#dropDownId option:selected').next().data('task-hours');

尝试为多个子任务循环但它不起作用:

var foo = [];
$('#dropDownId :selected').each(function(i, selected){
  foo[i] = $(selected).data('task-hours');
});

如何获取 total/combined 所选选项后下一个选项的值?

在上述情况下,总值应为 50 (child 1) + 50 (child 2) = 100 (parent task)子任务的总值不应超过父任务的值

你为什么不循环 it.First 得到选定的 value.Then 运行 循环如下。

注意:以下不是没有错误的代码,它就像一个逻辑或步骤。

var startfrom = $('#dropDownId option:selected').attr('value');

var alltext = "";
$('option').each(function(key,attr) {
{
if(key<startfrom) return;
alltext += attr.text;

}

console.log(alltext);
$("#dropDownId").on('change', function () {
    var a=$('#dropDownId option:selected+option').attr('data-task-hours');
    var b=$("#dropDownId option:selected").attr('data-task-hours');
    var c=Number(a)+Number(b);
    alert(c);
});

JS FIDDLE

您可以使用:

 var sum=0;
 alert($('select option:first').attr('data-task-hours'))
 $('select option:gt(0)').each(function(){
  sum+= parseInt($(this).attr('data-task-hours'));
 });
 if($('select option:first').attr('data-task-hours')==sum){
  alert("parent and children have same hours");
}

Working Demo

你在追求这样的东西吗?演示@Fiddle

var sOpt = $("#sel option:selected");
var nextOpts = sOpt.nextAll();
var sum = 0;
nextOpts.each(function() {
    sum += $(this).data("taskHours");
});
if ( sum > sOpt.data("taskHours") ) {
    alert ("Total is greater than parent");
} else {
    alert (sum);
}

HTML:

<select id="sel">
    <option data-task-hours="100" value="1" selected="selected"> - Parent Task</option>
    <option data-task-hours="50" value="2"> -  - Child task</option>
    <option data-task-hours="50" value="3"> -  - Child task</option>
</select>

这里有 nextAll() 方法:

var selectedOption = $('#dropDownId option:selected')
var selectedOptionValue = selectedOption.data('task-hours');
var sum = 0;
selectedOption.nextAll().each(function(){
    if (sum < selectedOptionValue) {
        sum += $(this).data('task-hours');
    } else {
        sum = selectedOptionValue;
        return false;
    }
});

这个有效:

var indexOfSelected = $("#dropDownId option:selected").index()
 var options = $("#dropDownId option")

 var children = options.slice(indexOfSelected + 1, options.length)

 total = 0
 $.each(children, function(){
     total += $(this).data("task-hours")
 });

console.log("Total sum of children: " + total)

试试这个Working Demo

$("#dropDownId").on('change', function () {
    var one=$('#dropDownId option:selected+option').attr('data-task-hours');
    var onetwo=$("#dropDownId option:selected").attr('data-task-hours');
    var onethree=Number(one)+Number(onetwo);
    console.log(onethree);
});