javascriptinputcustom-attribute

Add a field with custom attribute depending on number of fields


I need some help with js - im too noobish in it to figure how to do what I need. Searched for solution but it seems that my issue is quite specific. Right now I got a form with several fields and a button, that add one more field.

But I need not just another field, but a field with custom "name" and "placeholder" parameters, that depend on the number of the existing fields. Like if there are three fields, I need the function to create field with placeholder="Field 4" and name="start4".

Thanks for any help in advance!

Here's my code

function add_fields() {
    
   var d = document.getElementById("fields");
  
   d.innerHTML += "<label>Field #</label><br /><input  type='text' class='start1' name='start#' placeholder='Field #'/><br />";
}
<form action="" style="text-align: center;" method="get">

<div id="fields">
    <label>Field 1</label><br />
    <input  type="text" class="start1" name="start1" placeholder="Field 1"/><br />
    <label>Field 2</label><br />
    <input  type="text" class="start1" name="start2" placeholder="Field 2"/><br />
    <label>Field 3</label><br />
    <input  type="text" class="start1" name="start3" placeholder="Field 3"/><br />
</div>
<a class="button" onClick="add_fields()">Add field</a>

<input type="hidden" name="step" value="2"/><br /><br />
<input class="button" type="submit" value="Submit" />

</form>


Solution

  • If you don't know ahead of time how many fileds you will have you can just count the existing ones instead of using a counter.

    function add_fields() {
       var count= document.querySelectorAll("#fields input").length + 1; 
       var d = document.getElementById("fields");
       d.innerHTML += "<label>Field "+count+"</label><br /><input  type='text' class='start"+count+"' name='start"+count+"' placeholder='Field "+count+"'/><br />";
       return false;
    }
    

    Here's a fiddle.

    [Don't forget to return false in the function or else your link will be submitted!]