How to put maximum limit in a javascript?
Here is the part of my form that uploads multiple images. It has an add more button, that opens a new input field. Whenever the user clicks on add more button, one new input field is opened. However, I wish that after the 5th input field is opened, and the user clicks on add more again, no new field should get open (ie I wish to limit the size of input field to 5)
<div id="formdiv">
<form enctype="multipart/form-data" action="" method="post">
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
</div>
javascript that handles the working
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'img/x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
Can anyone help me in applying this maximum limit?
You need to set a counter acheive this. you can update your code as follows.
var count=0;
$('#add_more').click(function() {
if(count<5)
{
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
count++;
}
});
链接地址: http://www.djcxy.com/p/23556.html
上一篇: 使用WCF服务的联合身份验证提供程序