article

Monday, April 4, 2022

jQuery Preview Multiple Images

jQuery Preview Multiple Images

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>jQuery Preview Multiple Images</title>
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
		.hidden{
			display:none;
		}
    	#preview{
    		margin-top:50px;
    	}    	
		#preview img {
    		margin:10px;
    	}
	</style>
</head>
<body>
<div class="container">
	<div class="row">
		<h2><center>jQuery Preview Multiple Images </center></h2>
		<input type="file" name="file" id="file" class="hidden" multiple>
		<center><button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button></center>
		<div id="preview"></div>	
	</div>
</div>
<script>
$(document).ready(function(){
	$('#filebutton').click(function(){
		$('#file').click();
	});

	$('#file').change(function(){

		var name = $(this).val().split('\\').pop();
		var file = $(this)[0].files;
		if(name != ''){
			if(file.length >=2){
				$('#filetext').html(file.length + ' files ready to upload');
			}
			else{
				$('#filetext').html(name);
			}
		}
	});

	$('#file').on("change", previewImages);
});

function previewImages() {

  var $preview = $('#preview').empty();
  if (this.files) $.each(this.files, readAndPreview);

  function readAndPreview(i, file) {
    
    if (!/\.(jpe?g|png|gif)$/i.test(file.name)){
      return alert(file.name +" is not an image");
    } // else...
    
    var reader = new FileReader();

    $(reader).on("load", function() {
      $preview.append($("<img>", {src:this.result, height:200}));
    });

    reader.readAsDataURL(file);
    
  }

}
</script>
</body>
</html>

Related Post