简体   繁体   中英

How can I perform calculation in Javascript

I have 2 tables in a class:

public class Table1 {
    public string Name{set;get;}
    public string Price{set;get;}
}
public class Table2 {
    public string Name{set;get;}
    public string Price{set;get;}
}

I have two input fields, one have name from table1 and another name from table2, based on whatever Name a user selects from both tables. Jquery should add price based on two of the selected names.

$(document).on("click", "#buttonClick", function () {
    for (var price in data) {
        if () {

        }
    }
});

Question: how can i pass table1 Name and Price to jquery. When i click #buttonClick it should calculate price. For example:

Table1
Name       Price
RoomA      $22 
RoomB      $23

Table2
Name       Price
BuildingA  $33
BuildingB  $30

If i select RoomA from field1(Table1) and BuildingA from field2(Table2) then i should get output as $55. So how can i pass Name and Price from Table1 and Table2 to jquery. I am getting Name and Price from database.

Ok, for two dropdowns ( select s) described in following html:

<select id="roomz">
    <option value="0">Select a room...</option>
    <option value="22">Room A</option>
    <option value="23">Room B</option>
</select>
<select id="buildingz">
    <option value="0">Select a building...</option>
    <option value="22">Building A</option>
    <option value="23">Building B</option>
</select>

( value of each option should be the actual price),

you can listen for change event, get value s of each select , sum them and put result wherever you need (for example, to some <input id="result" type="text" /> .

JavaScript:

function calculate() {
    //get selected values
    var roomPrice = $("#roomz").val();
    var buildingPrice = $("#buildingz").val();

    //get sum of values
    var result = parseFloat(roomPrice) + parseFloat(buildingPrice);

    //put sum to result
    $("#result").val(result);//or val("$" + result) if you want to display dollar sign
}

$(document).ready(function(){
    //listen to 'change' event of several selects
    $(document).on("change", "#roomz,#buildingz", function (e) {
        calculate();
    });
});

Here is the Demo

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