How to select an image on a dynamically created tab and display it before submitting using jQuery

I am dynamically creating tabs and on each tab I display an image. I then allow a new image to be selected by the user to replace it. When the new image is selected on the first tab it is displayed (the original image displayed is replaced). However, on the subsequent tabs the original image is not replaced (the new image name is displayed). The image selected on subsequent tabs are displayed on the first tab. There is no error in the console.

My html:

//Column 2 to contain the image
            contents += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="photo">Photograph:</label>';
            contents += '<input class="form-control-file col-lg-8 col-md-8 col-sm-8 col-xs-8" type="file" id="photo" name="photo" placeholder="Photograph">';
            contents += '<img id="campImage" src="' + obj.eventPicture + '" alt="Camp image" class="img-thumbnail">';
            contents += '</div>';

js:

$(document).on('change', '#photo', function(){
			readURL(this);
		});
		
		function readURL(input) {
		    if (input.files && input.files[0]) {
		        var reader = new FileReader();
		        
		        reader.onload = function (e) {
		        	$('#campImage').attr('src', e.target.result);
		        }
		        
		        reader.readAsDataURL(input.files[0]);
		    }
		}

The answer to this is to make each “id=” unique. In this case id=“photo” needs to change to “id=”‘+obj.eventId+’"’ and "id=“campImage”"chages to “id=“campImage’+obj.eventId+'””.The eventId is the primary key for the row in the table and is therefore unique.

The code is:
//Column 2 to contain the image
contents += ‘

’;
contents += ‘Photograph:’;
contents += ‘’;
contents += ‘Camp image’;
contents += ‘
’;

So you now ask, if the “id” changes each time how do I recognise it has changed? Well in the class add a unique name, I use “photo-input” and use that. So the JS is:

            $(document).on('change', '.photo-input', function(){
		alert("this.id: " + this.id);
		readURL(this, this.id);
	});
	
	function readURL(input, id) {
	    if (input.files && input.files[0]) {
	        var reader = new FileReader();
	        
	        reader.onload = function (e) {
	        	$('#campImage'+id).attr('src', e.target.result);
	        }
	        
	        reader.readAsDataURL(input.files[0]);
	    }
	}

So, you will notice that I have id set to a unique value for each tab. I then append that value to the input id that I want to populate (picture is not the only one in this form, I have kept this simple).

This is HTML canon. All IDs must be unique. Names can be reused, but not IDs.

V/r,

^ _ ^

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.