Tanvir Sourov Tanvir Sourov - 4 months ago 18x
jQuery Question

Detect Input Value Change Inside PHP foreach from jQuery

I have a PHP foreach loop inside a form where the value comes from database. Here, the input ID increases with the element of the loop.

<form class="form-horizontal">
$count = 0;
foreach ($value as $row) {
$count += 1;
'<div class="row">
<div class="form-group">
<label id="durationLabel' . $count . '">Duration (days)</label>
<input type="number" name="duration_days" value="' . $row['duration_days'] . ' day" class="form-control input-sm" id="durationInput' . $count . '" placeholder="Days" onchange="durationInputChange(this.value,'.$count.')">

Now, my question is, how can I detect if any input value is changed (based on ID) and also get that value and show that in that corresponding Label using jQuery. The current JavaScript code I have doesn't do anything on value change:

function durationInputChange(a,i) {
var d = document.getElementById("durationInput"+i).value;


You cannot use change merely if you want more and faster feedback. The change is event is executed after blurring the input element. You can add keyup, keydown, and more like paste. Furthermore, you don't need the onchange attribute--no for inline binding and event listeners.

  $('input[name="input-1"]').on('keyup change paste keydown', function(){
    var $this = $(this); 
    console.log($this.attr('id')); // ID; for referencing 
    console.log($this.val()); // value of this input


input {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input name="input-1" value="" id="input-1">
<input name="input-1" value="" id="input-2">
<input name="input-1" value="" id="input-3">
<input name="input-1" value="" id="input-4">
<input name="input-1" value="" id="input-5">
<input name="input-1" value="" id="input-6">
<input name="input-1" value="" id="input-7">
<input name="input-1" value="" id="input-8">
<input name="input-1" value="" id="input-9">
<input name="input-1" value="" id="input-10">
<input name="input-1" value="" id="input-11">
<input name="input-1" value="" id="input-12">
<input name="input-1" value="" id="input-13">