问题
I was trying to make a simple computation out of these textboxes.
This is my code so far:
@foreach (var discount in Model.Discounts)
{
<div class="editor-label">
<label for="@discount.Key.DiscountCode">@discount.Key.DiscountName</label>
</div>
<div class="editor-field">
<input class="discountCode" name="discountCode" readonly="true" type="text" />
<a class="remove" data-key="discountCode" href="javascript:void(0);">Remove</a>
<a class="edit" data-key="discountCode" href="javascript:void(0);">Edit</a>
</div> <br />
}
<div class="totaldiscounts">
Total: <input id="total" type="text" />
</div>
<script>
$('.edit').on('click', function () {
var parent = $(this).parent();
var input = parent.find('input');
if (input.attr('readonly') === 'readonly') {
$(this).text('Stop Edit');
}
else {
$(this).text('Edit');
}
input.attr('readonly', !input.attr('readonly'));
});
$('.remove').on('click', function () {
var parent = $(this).parent();
var input = parent.find('input');
input[0].value = 0;
$(input).first().blur();
var parent = $(this).closest("div");
var uncle = parent.prev();
parent.remove();
uncle.remove();
});
$('.discountCode').on('blur', function () {
var inputs = $(".discountCode");
var val = 0;
for (var i = 0; i < inputs.length; i++) {
if (!isNaN(inputs[i].value)) {
val += +inputs[i].value;
}
}
$('#total').val(val);
});
</script>
This code works until I have to change the class name of each textboxes into their actual unique discount codes like this:
<input class="@Model.discount.discountCode" name="@Model.discount.discountCode" readonly="true" type="text" />
So apparently, my javascript no longer works because the classname of each textboxes are now different to each other.
How can I make my javascript work with this setup.
Any help will be greatly appreciated. Thank you!!
回答1:
Put the additional class name into element(example).
class="unique_class_name shared_class_name"
After all, loop to each class(shared_class_name), to get the value like following code :
$('.shared_class_name').on('blur', function ()....
来源:https://stackoverflow.com/questions/29737885/javascript-jquery-textbox-values-calculations