Using jQuery to dynamically add/remove form elements

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

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!
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13504
  • Loc: Florida

Post 3+ Months Ago

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>
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

*buys joe a drink*
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13504
  • Loc: Florida

Post 3+ Months Ago

Why thankyou sir. :beerchug:

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 56 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
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.