Photo by Tine Ivanič on Unsplash

Repeater form field with jQuery

Maayan Savir
2 min readJul 23, 2019

I worked on a client website where he has a form to be filled up by his users. One of the needs for the form was the ability to have a “repeater” field that is constructed from 2 inputs, where the user can add as many fields as he/she wants.

The field looks something like this

The user can add as many fields as he/she wants.

The HTML code

<div id="other-persons">
<h5>Add another participant</h5>
<div id="another-participant1">
<input type="text" name="other_participant[1][name]" placeholder="Name"/>
<input type="text" name="other_participant[1][id]" placeholder="Id"/> </div> <button type="button" id="add-participant">+ Add more</button>
</div>

I am using name=”other_participant[1][name]” and name=”other_participant[1][id]” so I will have a nice data structure once I will need to store the field data.

The jQuery code

based on this stackoverflow answer

$("#add-participant").click(function(){

// get the last DIV which ID starts with ^= "another-participant"
var $div = $('div[id^="another-participant"]:last');

// Read the Number from that DIV's ID (i.e: 1 from "another-participant1")
// And increment that number by 1
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

// Clone it and assign the new ID (i.e: from num 4 to ID "another-participant4")
var $klon = $div.clone().prop('id', 'another-participant'+num );

// for each of the inputs inside the dive, clear it's value and
// increment the number in the 'name' attribute by 1
$klon.find('input').each(function() {
this.value= "";
let name_number = this.name.match(/\d+/);
name_number++;
this.name = this.name.replace(/\[[0-9]\]+/, '['+name_number+']')
});
// Finally insert $klon after the last div
$div.after( $klon );

});

With this code, we can duplicate the inputs inside the div, each of them will have the same name but the array index will be different. This will let us store the data in good data structure -

other_participant =
[
1 => [id => "123", name => "foo"],
2 => [id => "456", name => "bar" ]]

After we achieved it, we can store the data as a JSON object in our database. With PHP is simple as

json_encode($_POST['other_participant']

This line will store the data like this

{“1”: {“id”: “123”, “name”: “foo”}, “2”: {“id”: “456”, “name”: “bar”} }

Hope you enjoyed it. For any comments/enhancements or something else you have to say about it, I would love to hear!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response