添加2个输入值并显示总错误

时间:2018-03-15 19:41:35

标签: javascript jquery

希望这是有道理的。我有2个输入字段将添加在一起并吐出总数。我有那个部分在工作。这是问题,假设我在input1中输入$ 200,在input2中输入$ 1000,但后来我想将input1更改为$ 300。总金额将达到301美元而不是1300美元。这是我的代码。

import UIKit
import PlaygroundSupport

public class VC: UIViewController {

    let view1 = UIView()
    let view2 = UIView()
    let view3 = UIView()
    var stackView: UIStackView!

    public init() {
        super.init(nibName: nil, bundle: nil)
    }

    public required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    public override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view1.backgroundColor = .red
        view2.backgroundColor = .green
        view3.backgroundColor = .blue

        view2.isHidden = true

        stackView = UIStackView(arrangedSubviews: [view1, view2, view3])
        stackView.spacing = 10
        stackView.axis = .horizontal
        stackView.distribution = .fillProportionally

        let uiSwitch = UISwitch()
        uiSwitch.addTarget(self, action: #selector(onSwitch), for: .valueChanged)

        view1.addSubview(uiSwitch)
        uiSwitch.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            uiSwitch.centerXAnchor.constraint(equalTo: view1.centerXAnchor),
            uiSwitch.centerYAnchor.constraint(equalTo: view1.centerYAnchor)
        ])

        view.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            stackView.heightAnchor.constraint(equalToConstant: 50),
            stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50),
            stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50)
        ])
    }

    @objc public func onSwitch(sender: Any) {
        view2.isHidden = !view2.isHidden
        if !view2.isHidden {
            stackView.setCustomSpacing(CGFloat(arc4random_uniform(40)), after: view2)
        }
    }
}

PlaygroundPage.current.liveView = VC()
PlaygroundPage.current.needsIndefiniteExecution = true

1 个答案:

答案 0 :(得分:0)

你的formatMoney方法中肯定会发生一些不好的事情,其余的似乎按预期工作。

例如:

$('#additionalPayment, #currentPayment').keyup(function() {
    updateTotal();
});

var updateTotal = function () {
    var input1 = parseInt($('#additionalPayment').val());
    var input2 = parseInt($('#currentPayment').val());
    var inputTotal = input1 + input2;

    if (isNaN(inputTotal)) {
        $('.totalPay').text('-');
    } else {
        $('.totalPay').text(formatMoney(inputTotal , 2));
    }
};

var formatMoney = function (val, places) {
    return ('$' + val.toFixed(places));
}