mercredi 14 septembre 2016

live update value if checkbox is checked or not

I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?

<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>




Aucun commentaire:

Enregistrer un commentaire