johnmoe johnmoe - 10 days ago 4
HTML Question

How to pass a value by clicking on an image in bootstrap modal back to the main page

I am trying to create a form where a button opens the bootstrap modal, and clicking on an image in the modal sends the filename of the image(without the extension would be best) back to the form.

The images in the modal dialogue are loaded from a folder with PHP.

Been at this for a long time and can't figure out how to do this when the images are called in PHP like this:(
Thank you in advance.

EDIT:The image filename should be passed to the textinput in the form.

Modal code:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="myModalLabel">Choose a picture</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Images</h1>
</div>

<?php
$files = glob("img/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
echo '
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="'.$image .'" />
</a>

</div>

'
;

}
?>

</div>
</div>
</div>
</div>
</div>


Main page code:

<button type="button" class="btn btn-info btn-lg"
data-toggle="modal" data-target="#myModal">Open Modal
</button>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Text
Input</label>
<div class="col-md-4">
<input id="textinput" name="textinput" placeholder="" class="form-
control input-md" type="text">
</div>
</div>

Answer

You can use cookies maybe:

<script>
function vars() {
   var x = document.cookie; 
    // alert(x); // uncomment this to check value
    // return x;  
    document.getElementById('textinput').value = x.split(';')[0].split('=')[1].split('.')[0];  // this give you the file name without extension in textbox   
}
function setcookies(img){
    document.cookie = "selected_img="+ img.split('/').pop();
}
</script>

The php part would be like this:

<?php
 $files = glob("img/*.*");
  for ($i=0; $i<count($files); $i++) {
      $image = $files[$i];
      echo '
      <div class="col-lg-3 col-md-4 col-xs-6 thumb">
        <a class="thumbnail" href="#">
            <img  class="img-responsive" src="'.$image .'" onclick="setcookies(this.src);vars();" />
        </a>

      </div>

      '
      ;

  }
?>

And after closing your modal you can have your var by calling vars() function. For example having this in main page.

<button type="button" class="btn btn-info btn-lg" 
  onclick="vars()" >vars
 </button>

or you can call the vars() right after setting cookie like this:

<img  class="img-responsive" src="'.$image .'" onclick="setcookies(this.src);vars()" />
Comments