Jonathan Ryan Patterson Jonathan Ryan Patterson - 2 months ago 6
jQuery Question

Dynamically adding ID to element within one of many forms on a page

I apologize if my title is a bit confusing. I couldn't think of a good way to title it.

Anyways, I'm looking for some help with some jQuery.

I have a page, that has 3 forms. All the form fields in each form get pre-populated with values and are disabled by default.

Each form has an "edit" link (all have the same class attached), that once clicked will remove the disabled property, display save and cancel buttons, and put focus on the first input field. I can accomplish this myself when I hardcode all the ID's I need. But that really isn't going to work for my situation.

The only unique identifier between each form is the form tag's ID.

What I'm trying to do is when the page loads, I want to add an ID to the edit link and also append the forms ID to that newly created ID for the edit link.

Here is a very basic code example to show what I'm working with:

<form id="form-1">
<a class="edit">Edit</a>
...
</form>
<form id="form-2">
<a class="edit">Edit</a>
...
</form>
<form id="form-3">
<a class="edit">Edit</a>
...
</form>


I'm looking to dynamically add an ID to each edit link, without having to explicitly set in the html. I want to add an ID of "edit-[form ID]", with [form ID] being the ID that of the form.

So after the page loads I want the forms to look like this:

<form id="form-1">
<a class="edit" id="edit-form-1">Edit</a>
...
</form>
<form id="form-2">
<a class="edit" id="edit-form-2">Edit</a>
...
</form>
<form id="form-3">
<a class="edit" id="edit-form-3">Edit</a>
...
</form>


Here is what I have tried so far, but can't get it to work properly.

$(document).ready(function(){
$("form").each( function(index) {
var formID = $("form").attr("id");
$(".edit").attr("id", "edit-" + formID );
});
});


Unfortunately, it is adding
id="edit-form-1"
to all the form edit links.

There are other elements in the form I need to do something similar with, but seeing one working example should help me with the rest.

Any help will be greatly appreciated.

Answer

Use this.id and the .edit child of this

$("form").each(function() {
    $(".edit", this).attr("id", "edit-" + this.id);
});

where $(".edit", this) is equivalent to $(this).find(".edit")

I must admit that it's a bit strange you need to add those ID... You can always do something like:

$(".edit").on("click", function() {

    var $myForm = $(this).closest("form");
    // Do something with $myForm

});

without ever carrying about form or button ID

Comments