我已经尝试过但有错误,但只有输入的百分比不是100%才会显示字段。例如,如果我在第一个百分比输入字段中输入22%而在第二个百分比输入字段中输入78%,则警报应该说百分比已达到100%但是如果未达到100%,则应继续添加输入字段,直到它们全部添加高达100%
$(document).ready(function () {
$(document).on("focusout", ".ration, .percentage", function () {
var count = $('.newtextbox').length;
if (count < 5) {
$(content).append("<p><input type='text' class='newtextbox' id='ingredient" + count + "' placeholder='ingredient name'/> <input type='text' class='costPerTon' placeholder='cost per ton'/> <input type='text' class='percentage' placeholder='percent applied'/> <input type='button' value='Remove' id='removeButton" + count + "'/></p>");
} else {
alert('You have maximum elements allowed.')
}
$("input[type = 'button']").click(function () {
$(this).parent().remove();
});
});
});
答案 0 :(得分:1)
您的示例无效,因为查询$(内容)错误。我想这里必须是$(“#content”)。
答案 1 :(得分:0)
据我了解,您的问题是如何计算在所有输入中输入的总%数。
以下是您执行此操作的方法:
var totalPercents = 0;
$("input").each(function (i, input) {
var percent = $(input).val().replace(/%/g, "");
if (!isNaN(percent)) {
totalPercents += parseInt(percent);
}
});
我相信你会弄清楚如何将它应用到你的代码中:)
答案 2 :(得分:0)
尝试这样的事情:
$('button').on('click', function () {
var current_percent_sum = $('.value').get().map(function (value) {
return $(value).data('value')
}).reduce(function (sum, value) {
return sum + value;
}, 0);
var pending_percent = +($('.percent').val());
if (current_percent_sum + pending_percent <= 100) {
$('body').append('<div class="value" data-value="'+ pending_percent +'">' + pending_percent + '</div>')
} else {
alert('You can only enter a max of ' + (100 - current_percent_sum));
}
});
答案 3 :(得分:0)
将答案应用于您的具体示例/小提琴:
$(document).ready(function () {
$(document).on("focusout", ".ration, .percentage", function () {
var count = $('.newtextbox').length;
var percent = 0;
$(".percentage").each(function (i) {
var pc = parseInt($(this).val().replace(/%/g, ""));
if (!isNaN(pc)) {
percent += pc;
}
});
if (percent == 100)
{
alert('Reached 100%');
}
else if (percent > 100)
{
alert('Oops, you are over 100%');
}
else if (count < 5) {
$('#content').append("<p><input type='text' class='newtextbox' id='ingredient" + count + "' placeholder='ingredient name'/> <input type='text' class='costPerTon' placeholder='cost per ton'/> <input type='text' class='percentage' placeholder='percent applied'/> <input type='button' value='Remove' id='removeButton" + count + "'/></p>");
} else {
alert('You have maximum elements allowed.')
}
$("input[type = 'button']").click(function () {
$(this).parent().remove();
});
});
});
这里的新小提琴:http://jsfiddle.net/F76Tk/