css 如何从文本区、复选框和单选按钮中获取值?

bihw5rsg  于 2023-03-14  发布在  其他
关注(0)|答案(2)|浏览(155)

我试图从所有表单域中获取结果。当我更改值并更改复选框时,总和的答案应该更改。如何从文本区域、复选框和单选按钮中获取总和的值?
下面是我的JavaScript代码:

$("document").ready(function () {
  $("#orderbutton").on("click", function () {
    var weight = parseFloat($("#weight").val());
    var destination = $("#destination").val();
    var insurance = $("#chkbox1").val();

    //construct output
    var msg = "<div> Result Of your order: </div>";
    msg += "<div> Package weight: " + weight + " pounds </div>";
    if (weight <= 25) {
      msg += "<div> Base cost based on your weight: $15.00  <div>";
    } else if (weight <= 50) {
      msg += "<div> Base cost based on your weight: $25.00 <div>";
    } else {
      msg += "<div> Base cost based on your weight: $40.00 </div>";
    }
    if (destination == "ny") {
      msg += "<div> Destination Selected: New York State( No extra cost)</div>";
    } else {
      msg += "<div> Destination Selected: Out Of State ($15.00 Extra)</div>";
    }
    if ($("#chkbox1").is(":checked")) {
      msg += "<div>Insurance option: Insurance Choosen($10.00 Added)<div>";
    } else {
      msg += "<div> Insurance option: Insurance Not Choosen($0.00 Added)</div>";
    }
    msg += "<div> Total price of order: </div>";

    $("#output").html(msg);
  }); // end event handler
}); // end document.ready

sample result image

dldeef67

dldeef671#

目前,您只计算订单按钮click上的所有内容。为了在文本区域、复选框和单选按钮发生变化时重新计算总和,您可以将.change()事件附加到表单元素中。
有关.change()的详细信息,请参阅https://api.jquery.com/change/

ztmd8pv5

ztmd8pv52#

用于获取文本区域值

var textareaValue = $("#myTextarea").val();

用于获取复选框值

var checkboxValue = $("#myCheckbox").is(":checked");

用于获取无线电值

var radioValue = $("input[name='myRadios']:checked").val();

用于计算总和

var sum = weight + (destination == "ny" ? 0 : 15) + (insurance ? 10 : 0);
msg += "<div> Total price of order: $" + sum.toFixed(2) + "</div>";

相关问题