weixin_33727510 2015-08-19 16:48 采纳率: 0%
浏览 18

实时计算?

I have searched through all of SOF and couldn't find any topic that matches my problem. I have written an HTML form that I will use PHP to process later, but I have some options in the form that a user can choose. Here is the HTML code

<label for="FIELD6">Model Type: </label><br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model"  checked  onclick="doMath()" />Normal Model<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath()" data-clicked="no" />Workshop Model
<p id="total"></p>

So the user can choose between a Normal and Workshop Model. I am trying to set it so that when the user checks the workshopmodel radio button, it adds to the total price (specified in paragraph tags). Here is my attempt at my barely-known language, jQuery:

function doMath() {
    var basePrice = 15;
    var baseModel = 0;
    var customModel = 5;
    var modelTotal = ;
    function workshopModel() {
        if(getElementById("workshopmodel").click(function() {
            modelTotal = basePrice + customModel;
        }
    }
    function defaultModel() {
        if(getElementById("basemodel").click(function() {
            modelTotal = total basePrice + baseModel;
        }
    }
}
$("#total").html('<font color="black">Total Price:</font><font color="#09ff00">' +  workshopModel() + '');

So I am trying to make it add to the basePrice in real time, and then print it in place of the ID marked "total" every time the user makes a change in selection (in real-time). So if the user chooses workshopmodel, the script will add 15 and 5, resulting in 20, and if they choose basemodel, the script will add 15 and 0, resulting in 15. I left the variable modelTotal undefined as it should be defined later on in the script. Can anyone help me out with this?

  • 写回答

2条回答 默认 最新

  • weixin_33694620 2015-08-19 17:07
    关注

    This should work how you want. Also, does not require jQuery.

    function doMath() {
        var basePrice = 15;
        var baseModel = 0;
        var customModel = 5;
        var modelTotal;
        if (document.querySelector('input[name="FIELD6"]:checked').value == "Normal Model") {
            modelTotal = basePrice + customModel;
        }
    
        if (document.querySelector('input[name="FIELD6"]:checked').value == "Workshop Model") {
            modelTotal = basePrice + baseModel;
        }
        console.log(modelTotal);
        document.getElementById('total').innerHTML = '<span style="color:black">Total Price:' + modelTotal + '</span>';
    }
    <label for="FIELD6">Model Type:</label>
    <br>
    <input type="radio" id="basemodel" name="FIELD6" value="Normal Model" onclick="doMath()" />Normal Model
    <br>
    <input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath()" />Workshop Model
    <div id="total"></div>

    </div>
    
    评论

报告相同问题?