0

I have this piece of JQuery code that allows me to show a hidden div when a checkbox is selected.

  <script>
  $(function() {
    // run the currently selected effect
    function runEffect() {
      // get effect type from
      var selectedEffect = $( "#effectTypes" ).val();

      // most effect types need no options passed by default
      var options = {};
      // some effects have required parameters
      if ( selectedEffect === "scale" ) {
        options = { percent: 100 };
      } else if ( selectedEffect === "size" ) {
        options = { to: { width: 280, height: 185 } };
      }

      // run the effect
      $( "#effect" ).show();
    };

    // set effect from select menu value
    $( "#button" ).click(function() {
      runEffect();
      return false;
    });

    $( "#effect" ).hide();
  });
  </script>

And inside of that hidden section, I have a link that will pull up another form input called add_sub_name.

<fieldset>
    <legend>Yes<input type="checkbox"></legend>
        <span class="subunits">
            <span title="add_sub_name">Additional Subunit Name:</span><br />
                <?= $form->render('add_sub_name'); ?>
            <br>
            <a href="#" id="button">Add another subunit?</a>
        </span>
        <div id="effect">
            <!--  <h3>Show</h3> -->
            <p>
                <span title="add_sub_name">Additional Subunit Name:</span><br />
                <?= $form->render('add_sub_name'); ?>
            </p><br>
        </div>
</fieldset>

This all works okay, but I'm wondering how I can change the form so that the add_sub_name input doesn't show up ONCE when selected, but instead, multiple times. For example, the user could create an infinite number of hmtl inputs called add_sub_name.

How can I make this happen?

UndefinedReference
  • 1,223
  • 4
  • 22
  • 52
  • I don't understand, how is the user creating those elements currently? all I see are toggling of pre-existing form elements – Ohgodwhy Mar 01 '14 at 02:44
  • @Ohgodwhy - Yeah, that's what I'm doing, just toggling hidden elements. But I'm wondering if there's a way to let that link create an infinite amount of these elements, if that makes sense. – UndefinedReference Mar 01 '14 at 02:55

1 Answers1

3

When the button is clicked, just insert the HTML that includes the input.

$("#button").click(function(e) {
    $('<div>' + 
        '<span title="add_sub_name">Additional Subunit Name:</span><br />' +
        '<input type="text" name="add_sub_name" />' +
      '</div>')
    .hide()
    .insertBefore(this)
    .slideDown();
});
Alpha Codemonkey
  • 3,242
  • 21
  • 26