开发者

PHP and jQuery update textbox with checkbox value

开发者 https://www.devze.com 2023-04-04 17:45 出处:网络
I have the following functionality I would like to build into a form using jQuery: I have a list of values:

I have the following functionality I would like to build into a form using jQuery:

I have a list of values: Invoice No: 110, Amount: 240.00 Invoice No: 111, Amount: 399.00 Invoice No: 112, Amount: 150.00

Next to each row there is a checkbox which is set to checked by default. Right at the bottom there is a textbox with the total 789.00 for the set of data. I开发者_开发百科 would like to update the textbox when one of the checkboxes are de-selected & selected with the total of invoice amounts which checkboxs are checked.

The form will then be submitted to itself with the value of the textbox set.

Any suggestions welcome, as I'm a noob with jQuery.


Just answered similar question here: jQuery - Getting total depending on which checkboxes are selected

put some css class to your invoice total span, ex: <span class="inv-total">120<span>.

then put your checkbox inside of your invoice <div>:

<div>
    <input type="checkbox" value="##inv if here ##" />
</div>

and then jQuery of course:

$(document).ready(function() {
    $("input[type=checkbox]").click(function(event) {
        var total = 0;
        $("input:checked").each(function() {
            total += parseInt($(this).parent().find('.inv-total').text().substring(1));
        });

        if (total == 0) {
            $('#total').val('');
        }
        else {
            $('#total').val('$' + total);
        }
    });
});

I haven't chanse to test it, but this is the idea.

Live example: http://jsfiddle.net/dH9Eb/2/


$('.checkbox').change(function () {

        var text-box-val = $('.textbox').val();

    if ($(this).attr("checked")) {
        var new-val = $('.textbox').val() + $(this).attr('value');
        $('.textbox').val(new-val);
    }
    else {
        var new-val = $('.textbox').val() - $(this).attr('value');
        $('.textbox').val(new-val);
    }

});


Here is a solution with html table to update amount when you click on a checkbox:

HTML:

<table id="invoices">
    <thead>
        <tr>
            <td>Invoice no</td>
            <td>Total</td>
            <td>include</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="invoiceId">112</td>
            <td class="amount">10</td>
            <td><input class="amountCheck" type="checkbox" checked="checked"/></td>
        </tr>
    </tbody>
</table>

jQuery:

$("#invoices .amountCheck").click(function() {
    var amount = parseInt($(this).closest("tr").find(".amount").text());
    if ($(this).is(":checked")) {
        total += amount;
    } else {
        total -= amount;
    }
    $("#invoiceTotal").val(total);
});

Don't forget to check if the total is correct on server side.

Working solution : jsFiddle

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号