Tishad Touhidul Tishad Touhidul - 1 month ago 4
jQuery Question

Find an element by partial ID and then find which id got selected in jQuery

So i have these items whose ids are like

#date_0
,
#date_1
, etc.

Here is my script :

$('[id*="date_"]').bind('change', function(event) {
var hour_id = $('[id*="date_"]').val();
console.log(hour_id);
});


what I want is that if I change
#date_5
, I get its value. But I am getting only
#date_0
's value.

What am I missing here?

Answer

You can use this to get the current element that was changed:

var hour_id = $(this).val();

When you are inside a callback in jQuery - this is a reference to the element that triggered the current event.
In your code - this is the element that was just changed.

Check this example:

$('[id*="date_"]').bind('change', function(event) {
  var hour_id = $(this).val();
  console.log(hour_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date_0" />
<input id="date_1" />