When i integrated your javascript into my user form its acting strange. If its within the form tag the “add button”, adds the button but then it disappears. I rearranged the code you provided by basically adding a form tag and copy/pased the code for your review.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>disable/enable button & control the number of fields to display</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style>
.added-field{padding:7px;}
#add-file-field{margin:10px;}
</style>
<script>
$(function(){
var tot = 0;
$('#add-file-field').click(function(){
$("#addField").append('<div class="added-field"><input type="file" name="data[]"><input type="submit" class="remove-btn" value="Remove"></div>');
tot ++;
if (tot == 5){
$(this).attr("disabled", "disabled");
}
});
$(document).on('click', '.remove-btn', function(event) {
$(this).parent().remove();
if (tot == 5){
$("#add-file-field").removeAttr("disabled");
}
tot--;
});
});
</script>
</head>
<body>
<form>
<div id="addField"></div>
<button id="add-file-field">Add Image</button>
</form>
</body>
</html>
This is because you have wrapped form tags around the button, so the browser is submitting the form every time you click on the button.
The best way to counteract this, is to pass a reference to the click event to your JavaScript function and then to prevent the form’s default behaviour.
You have this:
$('#add-file-field').click(function(){
$("#addField").append('<div class="added-field"><input type="file" name="data[]"><input type="submit" class="remove-btn" value="Remove"></div>');
tot ++;
if (tot == 5){
$(this).attr("disabled", "disabled");
}
});
Change it to this:
$('#add-file-field').click(function(e){
e.preventDefault();
$("#addField").append('<div class="added-field"><input type="file" name="data[]"><input type="submit" class="remove-btn" value="Remove"></div>');
tot ++;
if (tot == 5){
$(this).attr("disabled", "disabled");
}
});