6

I have a table that looks like the following.

<tr>
  <td>Link Name</td>
  <td><a href="#" class="edit">Edit</a></td>
</tr>

At the bottom of the table I have the following.

<tr>
  <form class="hidden create">
    <h3>Add Link</h3>
    ...
    <input type="hidden" name="form_id" value="{menu-id}" />
  </form>
</tr>

To avoid a massive page of HTML I thought it would be cool if jquery could copy the create form, tweak a few attributes then make it appear after the links row. The only query really is how..

So here are my questions.

1) How do I grab the create form and save it as variable with jquery?

2) How do I edit the hidden field? I know how to change attributes but how do I select the field it once the form is within a variable?

3) How do I paste this form into my table after the edit link on its own row? I need something like parent-parent-after?

Thanks loads

1
  • This doesn't answer your question but I feel I should point out that your second code block is invalid HTML because the <tr> doesn't contain any <td>s or <th>s. You should either add a <td> or move that block outside of the table. Commented Sep 9, 2010 at 14:41

3 Answers 3

12

1) Place a copy of the form in a variable:

var create_form = $('form.create').clone();

2) Get the hidden input from the variable:

create_form.find(':hidden[name=form_id]').doSomething()...

3) Place form after .edit link in the same row (I assume this is in an event handler):

$(this).closest('tr').find('a.edit').after( create_form );
Sign up to request clarification or add additional context in comments.

Comments

1
var form = $('#your-form').clone();

This creates a copy of the selected elements. The original is not manipulated if you use the form-variable now.

Editing hidden fields works exactly like manipulating other DOM-elements:

form.attr('action', 'some-new-action');

You can "paste" your form using several methods. Possible solutions would be:

form.appendTo('#some-parent');
form.after('#some-parent');

2 Comments

Thanks for the comprehensive answer, how would I alter an input element within the form after it has been cloned?
You can use all the available jQuery functions for traversing/manipulating: form.find('.some-input').attr('name', 'new-name').
0

visit http://api.jquery.com/clone/ for detailed explanation.

This is the quick preview

HTML

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

Javascript

$('.hello').clone().appendTo('.goodbye');

Output

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

Hope it helps..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.