简体   繁体   中英

Dynamically update total through dropdown

i have a bit of a dilemma, i am trying to make it so that when a user selects an option from a dropdown box it dynamically updates a total on the same page, without any reloading.

In other words i have 5 different options in a dropdown box (1,2,3,4,5) and if the user selects 1 it needs to put it through a simple equation, and then output it in a "total" box on the right, the problem i want to do this dynamically with no reloading, can anyone give me any advice or tips on what i should be using and any tutorials that might help (code etc...)

Thanks

That should be accomplished with Javascript. I can recommend using jQuery as a Javascript Framework http://jquery.com/

With that it is really easy to do what you want:

$("select").change(function(){
     var currentValue = parseInt($(this).find("option:selected").val());
     //do whatever calculation e.g
     result = currentValue * 2 + 1;
     //output result somewhere on the page e.g.
     $("#output").html(result);
})

// This is the jquery you have to use in your page with ddl

$(document).ready(function () {
        $("#FloorId").change(function () {
            var ddlValue = $(this).val();

                $.getJSON('calculate.php', { "Id": ddlValue }, function (obj) {
                    $("total").text(obj.value);
                });
        });
    });

Return total in calculate page

if you don't need to store it in a database a simple use of jquery on client side can do it. on the select change you retrieve the total from a input with "readonly" set and then add the current number the user have choose. remember to reset the select or an user can't add two time the same number:

$(document).ready(function(){
    $('select#add').change(function(){
     var  total = parseInt($('input#total').val())+parseInt($(this).val());
     $('input#total').val(total);
        $('select#add option[value=""]').attr('selected', true);
    });
});

see this http://jsfiddle.net/3TMK8/ for a working example with html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM