I have a variable list of inputs, with each item having a unique incrementing name, like so...
<input type="text" name="values[0]" value="some text">
<input type="text" name="values[1]" value="some other text">
<input type="text" name="values[2]" value="some more text">
...
<input type="text" name="values[n]" value="last text">
The whole page (including the values, which are essentially an array) is produced by a PHP script, but I want to have a button to dynamically add another textbox. Quite easily possible with jQuery's append(), but I can't figure out how to get the name of the appended input to be "values[n+1]". Ideas?
But I want to have a button to dynamically add another textbox. Quite easily possible with jQuery's append(), but I can't figure out how to get the name of the appended input to be "values[n+1]"
This is one way to do this:
$('#btn').click(function() {
var lastname = $('#inputs [name^=value]:last-child')[0].name;
var next = parseInt(lastname.match(/\d+/)[0]) + 1;
$('#inputs').append('<input type="text" name="values[' + next + ']" value="more more text">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs">
<input type="text" name="values[0]" value="some text">
<input type="text" name="values[1]" value="some other text">
<input type="text" name="values[2]" value="some more text">
</div>
<button id="btn">Append</button>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments