Using jQuery to dynamically add/remove form elements

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Joined: Sep 22, 2003
  • Posts: 6130
  • Loc: Seattle, WA
  • Status: Offline

Post December 2nd, 2008, 6:56 pm

I've got an HTML form for which I'd like my users to be able to add and remove form elements according to how many of that particular item they'd like to enter.

For example, let's say a user a creating a recipe, and they need to specify the ingredients. I'd like the user to be able to click "Add" to add a new text box for each new ingredient they're adding, with the ability to remove that ingredient if they change their mind.

Now here's the catch: I'd like the indices of the array of inputs to automatically re-number themselves when one is removed so that I can send a nice and tidy array to a CakePHP controller for processing.

I've fooled around with a few examples but haven't been able to get it to work the way I want. Javascript has never been my strong point so tips/suggestions are greatly appreciated!
The Beer Monocle. Classy.
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post December 2nd, 2008, 6:56 pm

  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13455
  • Loc: Florida
  • Status: Offline

Post December 2nd, 2008, 7:45 pm

Then don't touch the indices, leave them blank. The server will interpret multiple ingredient[]s as a zero-N array.

Code: [ Select ]
<input type="text" name="ingredient[]" value="" />


For dynamic addition/removal, it's easy enough to use the native DOM traversal keywords, rather than jQueries "$(this).parent().get(0)"

Code: [ Select ]
<li>
   <input .../>
   <input .../>
   <input type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"/>
</li>
  1. <li>
  2.    <input .../>
  3.    <input .../>
  4.    <input type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"/>
  5. </li>
Strong with this one, the sudo is.
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Joined: Sep 22, 2003
  • Posts: 6130
  • Loc: Seattle, WA
  • Status: Offline

Post December 2nd, 2008, 8:14 pm

*buys joe a drink*
The Beer Monocle. Classy.
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13455
  • Loc: Florida
  • Status: Offline

Post December 2nd, 2008, 8:43 pm

Why thankyou sir. :beerchug:
Strong with this one, the sudo is.

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 122 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.