jQuery Add/Remove Input Fields Dynamically with Limit

Adding or removing multiple input fields with a limit set. If you have added a certain limit of input fields you will get an alert or something. But before that, make sure that you have read the previous part of this tutorial jQuery Add/Remove Input Fields Dynamically

jqyer-add-remove-input-fields-part2

jQuery

So far, We have the below jQuery set up from previous tutorial.


$(document).ready(function(){
	//when the Add Filed button is clicked
	$("#add").click(function (e) {
		//Append a new row of code to the "#items" div
		$("#items").append('
'); }); $("body").on("click", ".delete", function (e) { $(this).parent("div").remove(); }); });

We can limit adding additional fields like below:

Limitation


var n = $("#items div").length;
if (n <=5) {
$("#items").append('
'); } else{ alert("Only five additional fields are allowed!") }

We are checking the length of the divs added inside of the #items div

If it is less than or equal to 5, then we can append another div otherwise we can show an alert.

So totally we can add only 5 additional input fields.

You can set your own limit.

That’s it for the tutorial


Anand Roshan

Author: Anand Roshan

An entrepreneur, programmer and a passionate artist who loves to work independently. Get social: Twitter | Google + | Artist Page

Leave a Reply

Your email address will not be published. Required fields are marked *