2

I'm looking for a way to add html elements to a form by using for example a button. I've been looking on a few examples out there but they are very big (like 3+ times the size of the actual form I want to build) so I'm wondering if there is a better way of fixing this.

My idea is something like this:

<form action='blabla.php' method='post'>
    <!-- Insert button here to add a new element -->
    <input type='text' name='desc_1'>
</form>

And by clicking the button, the following should be rendered:

<form action='blabla.php' method='post'>
    <!-- Insert button here to add a new element -->
    <input type='text' name='desc_1'>
    <input type='text' name='desc_2'>
</form>

I want a new input field to be created, without the page having to reload and loose ev data entered in the form. Guessing this is something I should achieve through javascript or even jquery. I know how to edit an existing input field but I have no clue on how to create a new one and make it follow its numberrange. Anyone have an idea on how to apporoach this with a javascript function? Or should I invest in some time researching jquery for a smoother solution?

Dave
  • 253
  • 6
  • 14
  • possible duplicate of [Adding input elements dynamically to form](http://stackoverflow.com/questions/14853779/adding-input-elements-dynamically-to-form) – Mihai Matei Feb 13 '15 at 09:24

4 Answers4

5

You can do

html

<button onclick="create();">Create Field</button><br><br>
<form id="frm">

    <input type='text' name='desc_1' placeholder="Input Field 1"><br>
</form>

javascript

var count=1;
function create(){
//alert();
    count++;
    document.getElementById('frm').innerHTML+='<br/><input type="text" id="'+count+'" placeholder="Input Field'+count+'"  /><br/>';
    e.prventDefault();
}

FIDDLE

singhakash
  • 7,891
  • 6
  • 31
  • 65
1

$("button").click(function(){
    var count = $("input").length + 1;
    
    $("form").prepend("<input type='text' value='desc_" + count + "' name='desc_" + count + "'><br>");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<button>add input</button>
<br>

<form action='blabla.php' method='post'>
    <input type='text' name='desc_1'>
</form>

EXAMPLE

Ivošš
  • 1,106
  • 12
  • 18
  • 1
    I wish I could give mulitple correct answers. I really liked this, however the one I accepted doesn't require a lib. Well done. though! – Dave Feb 16 '15 at 16:23
0

AJAX is your answer. It will let you update a website content without needing to refresh the page over and over again.

Community
  • 1
  • 1
dHoja
  • 206
  • 3
  • 10
0

the salution your looking for is posible with XMLhttpRequest. http://www.w3schools.com/xml/xml_http.asp http://www.w3schools.com/dom/tryit.asp?filename=try_dom_xmlhttprequest_first good luck

Ivan Sander de Jong
  • 835
  • 1
  • 11
  • 28