'Using jQuery to insert PHP variable into form input
I have been staring at this problem for hours, but my jQuery skills are quite basic, so please I need some help here.
I have a 3 form inputs. When I click on one of the inputs it opens a bootstrap modal that contains my image gallery (which is populated by PHP), and below each image is an "Insert" button.
When I click the Insert button I wish to pass the title of that image back into the specific input field that I clicked.
I know this should be done with jQuery using "this" but just cant figure it out.
Here is my code so far:
The form fields
<form>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter">
</div>
</form>
My image gallery code (with insert button)
<?php
$query = $conn->query("SELECT * FROM images ORDER BY id DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageURL = '../../images/'.$row["file_name"];
$imageTitle = $row['file_name'];
$imageID = $row['id'];
?>
<div class="image-gallery-item">
<div class="image-gallery-img">
<img class="gallery-img" src="<?php echo $imageURL; ?>" alt="" />
</div>
<p class="mt-2"><?php echo $imageTitle; ?></p>
<button onclick="insert('<?= $imageTitle; ?>')" class="btn btn-primary" type="button" data-dismiss="modal">INSERT IMAGE</button>
</div>
My ineffective piece of jQuery
$(document).ready(function(){
$(".image_up").click(function insert(image){
$(this).val(image);
});
});
Any help would be greatly appreciated!
Solution 1:[1]
$(document).ready(function(){
$(".image_up").click(function insert(image){
$(this).val(image);
});
});
Should be changed to:
function insert(image){
document.querySelector('input[data-caller=' + document.getElementById('exampleModalCenter').dataset.caller + ']').value = image;
}
Also add this:
$('#exampleModalCenter').on('shown.bs.modal', function(e) {
this.dataset.caller = e.relatedTarget.dataset.caller;
});
Then on all of of your form text input add data-caller="". And give each of them a unique value. Like:
<form>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter" data-caller="first">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter" data-caller="second">
</div>
<div>
<input type="text" class="image_up" data-toggle="modal" data-target="#exampleModalCenter" data-caller="third">
</div>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
