0

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">

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Basically i have a small problem, When i console.log(num) returns NaN. Any suggestions?
Please provide some code example (jsFiddle) in order for us to be able to help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.