0

Following this post, I am trying to bind a keydow event handler on all dynamically elements which id starts with id_phone- and finished with -value. For example, id_phone-3-value should math, whereas id-phone-3-value should not.

To achieve this, I tried to come up with the code below:

$(document).on('keydown', '[id^=id_phone-_][id$=_-value]', function(){
   console.log('test');
});

...which, unfortunately, does not work for me. What am I doing wrong here ?

Community
  • 1
  • 1
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

1

The problem is the _ in your selectors. Your selector will match something like id_phone-_3_-value, but the IDs you want to match don't have underscores around the number.

$(document).on('keydown', '[id^=id_phone-][id$=-value]', function(){
   console.log('test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This should trigger: <input id="id_phone-3-value" type="text"><br>
This should not trigger: <input id="id-phone-3-value" type="text">
Barmar
  • 741,623
  • 53
  • 500
  • 612