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

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

本文关键字:选项 下拉列表 获取 下一个 之后 属性 jQuery      更新时间:2023-09-26

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');
});

如何在所选选项之后获取下一个选项的总/组合值?

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

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;
    }
});

你为什么不循环它。首先获取所选值。然后像下面这样运行循环。

注意:下面不是无差错的代码,它就像alogirthm或步骤一样。

var startfrom = $('#dropDownId option:selected').attr('value');
var alltext = "";
$('option').each(function(key,attr) {
{
if(key<startfrom) return;
alltext += attr.text;
}
console.log(alltext);

您可以使用:

 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");
}

工作演示

$("#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 小提琴

你在追求这样的事情吗?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>

这有效:

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)

试试这个工作演示

$("#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);
});