Use jQUERY on repeating Form, which increase ID subsequently

I have a Front End Form, which edits Posts in a WordPress Loop.

This means, on a certain page, I Loop through a Custom Post Type, and for each returned Post, I render a Form which edits the Post in the Loop, instead of the Post itself.

Read More

This creates a Form ID like this, for each form:

  • first post in loop: cred_form_1096_1
  • second post in loop:cred_form_1096_2
  • third form in loop: cred_form_1096_3

etc.

The number of Forms is dynamic, as it is a Loop returning certain content based on certain parameters.
There might be only 3 forms in the loop, on another day, there might be 5, because some new posts where published.

I use this jQuery to send the form via AJAX, when “Submit” is clicked:

jQuery(document).ready(function() { 
jQuery('#cred_form_1096_1').ajaxForm(function() { 
    alert("Thank you for your comment!"); 
}); 
}); 

of course the above only works on first Form in Loop, and for the second Form in Loop, and third, etc, I would need to manually adapt the ID each time!
(#cred_form_1096_2, #cred_form_1096_3 etc)

Is there a way to (example) use some thing similar as:
#cred_form_1096_$ ?

Means, the last number in the Form ID should adapt according to the form in Loop.

Or even better, it should just “use” any number in the last position
like: cred_form_1096_any

If it’s the first form in the loop, use cred_form_1096_1, if it’s the second, use cred_form_1096_2, etc.

Not sure at all this can be done?

Any inputs are welcome.

UPDATE::

The first answer here worked like charm, I am sure all other do too!

jQuery(document).ready(function() { 
jQuery("[id^=cred_form_1096]").ajaxForm(function() { 
    alert("Thank you for your comment!"); 
}); 
}); 

I use now ("[id^=PART_OF_ID]")

Related posts

2 comments

  1. Hm,

    you should consider using attribute selector to achieve this.

    You can target f.e. form with id which starts with PART_OF_ID:

    $("[id^=PART_OF_ID]").ajaxForm(function () { ...
    

    You can also seek for all elements which contain (*=) or end up with ($=) known part of ID/class/type f.e.

  2. Say that i is an increment value. You could simply do:

    $('#cred_form_1096_'+i)
    

Comments are closed.