Javascript/JQuery Textbox Values Calculations

走远了吗. 提交于 2019-12-13 07:59:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!