cucuru cucuru - 1 year ago 75
jQuery Question

get the id starting with

I have a datepicker in a div with class pickergroup, I have 3 datepicker in my page, and this is why I use a group and different names

<div class="pickergroup">
<input type="text" name="day1" id="day1"/> /
<input type="text" name="month1" id="month1"/> /
<input type="text" name="year1" id="year1"/>
<input type="hidden" id="date1" name="date1"/>
<div id="datepicker1" name="calendar"></div>

In my jquery I want to detect when clicking the id wich starts with "datepicker", I guess something like:

$(document).on('click', '.pickergroup id^="datepicker"', function() {
//my datepicker code

but this is not correct.

how can I do it?

Answer Source

The problem is how you're selecting the element inside of the event handler.


means "find all elements with the class of pickergroup. Find all of their children which have an ID starting with datepicker." Instead, you want to use this and fix your selector from

.pickergroup id^="datepicker"


.pickergroup [id^="datepicker"]

$(document).on('click', '.pickergroup [id^="datepicker"]', function() {
  var $this = $(this); // The div that was clicked
.pickergroup div {
  float: left;
  margin-right: 1em;
  width: 200px;
  height: 200px;
  background: #0F0;
<script src=""></script>
<div class="pickergroup">
  <div id="datepicker1">A</div>
<div class="pickergroup">
  <div id="datepicker2">B</div>
<div class="pickergroup">
  <div id="datepicker3">C</div>
<div class="pickergroup">
  <div id="can-t-click-me">D</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download