CGS CGS - 7 months ago 15
Javascript Question

Auto-Double Application

I am trying to create a quick program that will auto-Double the number that is entered in the text box.

My issue is that nothing happens when I enter a number in the text box.

What I want to happen is take the number that is input in the text box and automatically have the number doubled in the adjacent text box.



Question

What do I need to alter in my code so that the double of the number entered automatically populates in the second text box?


Code I tried

PHP/HTML

<body>
<form id="Form1" runat="server">
<div id="Form1" runat="server">
<table id="table1" border="1">
<tr>
<td>
<input type="text" id="txt_number1" name="txtnumber1input" value="0" maxlength="10" size="3">
</td>
<td>
<input type="text" id="txt_number1_doubled" name="txtnumber1doubled" value="0" maxlength="10" size="3" readonly>
</td>
</tr>
<tr>
<td>
<input type="text" id="txt_number2" name="txtnumber2input" value="0" maxlength="10" size="3">
</td>
<td>
<input type="text" id="txt_number2_doubled" name="txtnumber2doubled" value="0" maxlength="10" size="3" readonly>
</td>
</tr>
</table>
</div>
</form>
</body>





JS


function DoMath(el) {
var id = el.attr("id").replace("txt_", "");
var lbltext = document.getElementById($("#txt_" + id)).innerHTML*2;
window.alert(lbltext);
}
$("#txt_number1, txt_number2").on("keyup", function() {
DoMath($(this));
});

Answer

You made some mistakes with selecting of elements

function DoMath(el) {
 id = el.attr('id')+"_doubled";
 $("#"+id).val(el.val()*2);
}

$("#txt_number1, #txt_number2").on("keyup", function() { DoMath($(this)); });
Comments