I have made a user profile card where the user can click on choose file to select and upload an image.
Everything works fine however I would like to change it so instead of having to click on “choose file” and then click on “upload”, the user can just click on the existing image and be brought to the select image screen:
and once they have selected a image and pressed open, the image is automatically changed?
This is my code to display the user profile card.
<?php //query to see if the user has uploaded a profile picture. $sql = "SELECT * FROM user_image WHERE userid = ?"; $stmt = mysqli_prepare($connect, $sql); mysqli_stmt_bind_param($stmt,"i",$_SESSION['userid']); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $userImage = mysqli_fetch_assoc($result); mysqli_stmt_close($stmt); ?> <h1>User's Profile</h1> <?php if($userImage['is_set'] == 0){ echo '<img src="profile_pics/default-profile-pic.png"/>'; } else{ echo '<img src="'.$userImage['image_dir'].'"/>'; } ?> <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="file" accept="image/*"> <button type="submit" name="submit">Upload</button> </form>
Advertisement
Answer
You can use a <label>
tag attached the file input to trigger the open box or you can use a click handler on the image that triggers a click on the file input.
document.querySelector('img').addEventListener('click', function(){ document.querySelector('h1 + img').click(); });
To get the file to upload immediately when selected you have to attach a change event handler for the image input. Then submit the form in it. You would have to change the submit button name to something other than submit to get this to work.
document.querySelector('input[type=file]').addEventListener('change', function(){ this.form.submit(); });
<button type="submit" name="upload">Upload</button>