Rilcon42 Rilcon42 - 1 year ago 82
Javascript Question

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?

<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;
alert("Error in input");

var j = document.getElementById("output");
if (this.checked) {
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<input type="text" id="output" value="Output" />

Answer Source

Place the <script> tag after <form>


When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.