javascript - hidden input value from php foreach loop not properly passing to JQuery -
html + php :
<?php foreach ($resultpics $row1){ ?> <div class="col-md-2"> <a href="#" class="thumbnail" data-popup-open="popup-1"<!-onclick="showimg(<?php //echo $row1['img_id']; ?>-->)"> <input type="hidden" name="imgid" value="<?php echo $row1['img_id']; ?>" id="imgid"> <img id="popimg" src="<?php echo $row1['img_path'];?>/<?php echo $row1['img_id']; ?>.jpg" alt="pulpit rock" style="width:200px;height:150px;"> </a> </div> <?php } ?>
jquery:
$('[data-popup-open]').on('click', function(e) { var targeted_popup_class = jquery(this).attr('data-popup-open'); $('[data-popup="' + targeted_popup_class + '"]').fadein(350); var imgid = $('input[name=imgid]').val(); alert(imgid); $('img#viewimg').attr('src','images/'+imgid+'.jpg'); e.preventdefault(); });
the problem value of
var imgidsame(on every different gives imgid of first image only). note there no problem in php foreach loop, fetch's correctly.
the problem have multiple input elements having name="imgid". when query $('input[name=imgid]') jquery parses of dom , creates object having 0 'n' input tags (n being number of elements matching query). if use val() on object return value of 0'th element in object.
solution:
change this
var imgid = $('input[name=imgid]').val();
to this
var imgid = $(this).next().val();
Comments
Post a Comment