0

I'm not really sure the best way to go about this but I've laid the framework.

Basically, I would like to add the functionality so that when my #moreItems_add button is clicked and calls the moreItems function, I simply want to add a new Input field below it, and so on. I want to limit this to 10 fields though, so I show that in the function.

The only trick is, I will be submitting all fields via ajax to save to the database, so I need to try and keep track of an ID with each.

What's the best way to continue the javascript here so that I can append an input field on button press and keep track of IDs for each?

<div class="modal-body">
    <form id="Items">
        <label id="ItemLabel">Item 1:</label>
        <input type="text" name="Items[]">
        <button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
    </form>
</div>
<div class="modal-footer">
    <input type="submit" name="saveItems" value="Save  Items">
</div>


<!--  modal JS -->
<script type="text/javascript">

    function moreItems(){
        var MaxItems = 10;

        //If less than 10, add another input field
    }

</script>
Geoff_S
  • 4,917
  • 7
  • 43
  • 133
  • 1
    If you are using jQuery, see the [`append()` method](http://api.jquery.com/append/). For AJAX submission, see [`serialize()`](http://api.jquery.com/serialize/). – showdev Sep 11 '18 at 20:04
  • So I could use that to add the new field on the front end, but then I would need to use serialize in the ajax call to insert each one from the form, right? – Geoff_S Sep 11 '18 at 20:09
  • Yes, you can use `append()` to append HTML elements to the DOM. You can use `serialize()` to "[e]ncode a set of form elements as a string for submission." I usually use it to serialize the entire form into a "data" variable. I suggest giving it a try and then, if you get stuck, let us know what you tried and what went wrong. – showdev Sep 11 '18 at 20:11
  • SO I tried this: ```function addTickerItem(){ var node = document.createElement("input"); document.getElementById("#tickerItems").appendChild(node); }``` but the button just refreshes the page – Geoff_S Sep 11 '18 at 20:15
  • Please see [How to prevent buttons from submitting forms](https://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms). – showdev Sep 11 '18 at 20:19

4 Answers4

1

You can use the jQuery .insertBefore() method to insert elements right before "more items" button. Below is the code representing this:

var maxItems = 1;
function moreItems() {
  if (maxItems < 10) {
  
    var label = document.createElement("label");
    label.id="ItemLabel"+maxItems;
    label.innerHTML = "Item "+(maxItems+1)+": ";
    var input = document.createElement("input");
    input.type='text';
    input.name = 'item'+maxItems;
    
    $('<br/>').insertBefore("#moreItems_add");
    $(label).insertBefore("#moreItems_add");
    $(input).insertBefore("#moreItems_add");
    maxItems++;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
    <form id="Items">
        <label id="ItemLabel">Item 1:</label>
        <input type="text" name="Items[]">
        <button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
    </form>
</div>
<div class="modal-footer">
    <input type="submit" name="saveItems" value="Save  Items">
</div>
Ashish Patel
  • 357
  • 4
  • 15
  • Thank you, this works. Is there a way to get them to display vertically though? Like a column – Geoff_S Sep 11 '18 at 22:50
  • You can add a
    tag between the input fields to align them properly. I've updated the answer with a 'label' tag and 'br' tag. so that it works as intended.
    – Ashish Patel Sep 11 '18 at 23:05
  • This worked perfectly, but I have multiple forms populating from an array loop now. Can you alter this so that it would work as if it were produced within a loop, so that the form/button had keys or IDs? – Geoff_S Sep 12 '18 at 20:02
  • I’ll do that from a PC. I’m currently on mobile. Can you elaborate or provide some code for the loops you want to implement? – Ashish Patel Sep 12 '18 at 23:50
0

Something like this should do the trick:

<!--  modal JS -->
<script type="text/javascript">
    var MAX_ITEMS = 10,
        added = 0;

    function moreItems(){
        if (added >= MAX_ITEMS) return;

        var newField = document.createElement('input');
        newField.type = 'text';
        //  TODO: Any field setup.

        document.getElementById('items').appendChild(newField);
        added++;
    }
</script>

In terms of tracking each field with an ID, that should always be done by the back-end for data integrity and safety reasons.

robinsax
  • 1,195
  • 5
  • 9
0

some years ago I've wrote an article about making a repeated section using jQuery.

The live example is available on jsFiddle.

In the example you can find that both "add" and "remove" button are available, however you can set just the "add" button for your purpose.

The idea to limit to specific number of repeated boxes is to watch the number of repeatable elements just created in the context. The part of code to change in the live example is rows 13-18:

        // Cloning the container with events
        var clonedSection = $(theContainer).clone(true);  

        // And appending it just after the current container  
        $(clonedSection).insertAfter(theContainer);  

There you should check if the number of repeated elements is less than <your desired number> then you will allow the item to be created, else you can do something else (like notice the user about limit reached).

0

Try this:

const maxItens = 10,
let itensCount = 0;

function moreItems() {
   if (itensCount++ >= maxItens) {
      return false;
   } 

   let newInput = document.createElement('input');

   // use the iterator to make an unique id and name (to submit multiples)
   newInput.id = `Items[${itensCount}]`;
   newInput.name = `Items[${itensCount}]`;

   document.getElementById('items').appendChild(newInput);

   return false;
}

Add type "button" to stop submiting the page (also, your button have two ID):

<button id="moreItems_add" onclick="moreItems();" type="button">More Items</button>

The submit button must be inside the form to work:

    <form>
        <div class="modal-body">
            <div id="Items">
                <label id="ItemLabel">Item 1:</label>
                <input type="text" name="Items[]">
            </div>
            <button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
        </div>
        <div class="modal-footer">
            <button type="submit">Save  Items</button>
        </div>
    </form>

To append itens in sequence the button must be outside of div "itens".

ThiagoYou
  • 308
  • 3
  • 12