我会提出一个建议,而不是为每个输入查看不同的元素,而是将标题文本存储为input
自身的属性。该title
属性非常适合此。
考虑到这一点,以下代码片段应该可以工作:
HTML:
为了清楚起见,略微简化。我在表单、输入和摘要元素中添加了类。
<form class="order-form">
<table>
<tr>
<td><input type="number" class="quantity" title="Product 1"/></td>
</tr>
<tr>
<td><input type="number" class="quantity" title="Product 2"/></td>
</tr>
<tr>
<td><input type="number" class="quantity" title="Product 3"/></td>
</tr>
</table>
<div class="order-form-summary"></div>
</form>
Javascript:
$(function(){
// Find all of the DOM elements we're interested in:
var form = $('form.order-form'),
output = form.find('.order-form-summary'),
inputs = form.find('input.quantity');
// Bind a custom event handler to the form, that collects the titles from the
// inputs with a value > 0
form.bind('updateSummary', function(){
// Collect the titles into an array
var summaries = $.map(inputs, function(e){
var input = $(e);
if (parseInt(input.val()) > 0){
return input.attr('title');
}
});
// Update the output element's HTML with the array, joined to a string with commas.
output.html(summaries.join(', '));
});
// Fire the update event whenever chance, key-up or blur occurs on any input
inputs.on('change keyup blur', function(){form.trigger('updateSummary')});
// Fire it on load to get the correct starting values (in case any inputs are already filled)
form.trigger('updateSummary');
});
这段代码可以压缩,但我的目标是让它可读。这是一个例子:https ://jsfiddle.net/ejwLy5x8/