Bipin Chandra Tripathi
Bipin Chandra Tripathi

Reputation: 2620

How to select dynamic id generated by php script

It's weird but I found all article not working for me. I have ids in my forms like formup_1, formup_2 generated by PHP scripts. Now I'm not able to select a particular id. How can I do that. Do I have to use live for binding event?

I tried to do it like this:

var vvv=$("form[id^='rating_formup_']");


<form id="rating_formup_1">
<input type="submit" name="n" value="">
</form>
<form id="rating_formup_2">
<input type="submit" name="n" value="">
</form>
.
.
.

Upvotes: 1

Views: 184

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

Just try with this

$('form[id^="rating_formup_"]'); // select any form id start with rating_formup_

To bind event you can try

$('form[id^="rating_formup_"]').on('click', function() {
 // your stuff
});

or

$('form[id^="rating_formup_"]').each(function() {
  $(this).on('click', function() {
    // do something 
  });
});

Remainder

  • recheck for typing errors

  • don't forget to include jQuery library

  • place your code within $(document).ready(function() {...}) , in short $(function() {..}).

Upvotes: 1

gdoron
gdoron

Reputation: 150253

$('form[id^="rating_formup_"]').foo();

It will select all the <form> elements that their id starts with formup

You can also use:

$('form').filter(function(){
    return /^rating_formup_/.test(this.id);
});

Which might be a little bit faster.

If you do that and it's still not working:

  1. Check for typos.
  2. Make sure the DOM is ready.
  3. If the <form> are created on the fly, make sure you query the DOM after they are inserted to the DOM.

Upvotes: 4

Related Questions