Makis
Makis

Reputation: 1254

jQuery - Onclick append form inputs and assign name attribute

I have a jQuery button that every time is pressed appends the inputs below to a form. My problem is that i need a way to also give name attributes (numbers) to the new inputs that jQuery produces.

1: <input type="file">
2: <input type="file">
3: <input type="file">
4: <input type="file">

Upvotes: 0

Views: 1498

Answers (1)

kapantzak
kapantzak

Reputation: 11750

Each time you click on #button get the last input and set the new name attribute. Then append the new input element in to the form:

$('#button').on('click', function() {
   var form = $('#form');
   var num = parseInt(form.find('input:last-of-type').attr('name')) + 1;
   form.append('<input type="file" name="' + num + '" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form">
  <input type="file" name="1" />
</form>

<button id="button">Add new</button>

Upvotes: 2

Related Questions