如果选中复选框,则为实时更新值

时间:2016-09-15 04:32:53

标签: javascript jquery checkbox

我正在尝试根据是否选中复选框来更新文本框。感谢this post我的文本框工作正常,但我无法获得更新值的复选框。我错过了什么?

<html>
<head>
    <title>sum totals</title>
    <script type="text/javascript">

        function calculate(t){
        var j = document.getElementById("output");
        var rege = /^[0-9]*$/;
        if ( rege.test(t.tons.value) ) {
            var treesSaved = t.tons.value * 17;
            j.value = treesSaved;
        }
        else
            alert("Error in input");
        }

  $('input[name="selectedItems1"]').click(function(){
    var j = document.getElementById("output");
    if (this.checked) {
      j.value=j.value+300
    }else{
      j.value=j.value-300
    }
  });
    </script>
</head>
<body>
    <form>
        <input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
        <br />
        <input type="checkbox" name="selectedItems1" value="val1" />I have a car
        <br/>
        <input type="text" id="output" value="Output" />
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

<script>标记放在<form>

之后

<强>原因

当html页面加载时,它将被逐行解释。当它来到click()时,jQuery将尝试找到当时不会被加载到DOM中的元素input[name="selectedItems1"]。因此,jQuery不会将click()事件句柄附加到该复选框。这就是您的代码无法正常工作的原因。

答案 1 :(得分:0)

试试这个:

<html>
<head>
    <title>sum totals</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
    <script type="text/javascript">

        function calculate(){
        var j = document.getElementById("output");
        var rege = /^[0-9]*$/;
        var tons = $('#tons').val();
        if ( rege.test(tons) ) {
            val = parseInt(tons);
            var treesSaved = val * 17;
            if($('input[name="selectedItems1"]').is(":checked"))
            {
                treesSaved = treesSaved +300;
            }
            else
            {
                treesSaved = treesSaved -300;
            }
            if(isNaN(treesSaved))
                j.value=0
            else
                j.value=treesSaved;
        }
        else
            alert("Error in input");
        }
$(function(){
  $('input[name="selectedItems1"]').change(function(){
    calculate();
});
});
    </script>
</head>
<body>
    <form>
        <input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
        <br />
        <input type="checkbox" name="selectedItems1" value="val1" />I have a car
        <br/>
        <input type="text" id="output" value="Output" />
    </form>
</body>
</html>