I have an input field from the beginning, with which I want to make calculations that update immediately when changing the value. Then I want to be able to add more input fields and also have them change the values when editing their content, without pressing any update button afterwards.
This code does this, but now it fires the calculating function several times if I add more input fileds and then edit one of the first input fields. I could remove line 4-6 (from the bottom) to get rid of the extra function triggering, but then the added input fields wont't work on the fly. Any ideas on how to solve this?
HTML:
<input type="number">
<table>
<tr>
<td id="linkedEventList">
<ol>
</ol>
<button id="btn">Add input fields</button>
</td>
</tr>
</table>
Jquery/Javascript:
jQuery(function($) {
$('input').on('input', function(e) {
calculate();
});
});
function calculate() {
alert("Checking how many times this function runs");
}
$(document).ready(function() {
$("#btn").click(function() {
$("#linkedEventList ol").append("<li ><input type='text'></input></li>");
$('input').on('input', function(e) {
calculate();
});
});
calculate();
});
You simply need to bind the handler once as such. You're binding on every click the way you have it currently. Also you're already using a 'ready' shortcut, so the additional document.ready is unnecessary.
jQuery(function($) {
function calculate() {
console.log("calculate");
}
$("#btn").click(function() {
$("#linkedEventList ol").append("<li><input type='text'></input></li>");
});
$(document).on('input','input', function(){
calculate();
});
calculate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">
<table>
<tr>
<td id="linkedEventList">
<ol>
</ol>
<button id="btn">Add input fields</button>
</td>
</tr>
</table>