Array in php each record goes inside a hidden div
$array=(15,20,50,23,10);
record list (loop)
<div>15</div> position 1
<div>20</div> position 2
<div>50</div> position 3
<div>23</div> position 4
<div>10</div> position 5
The code is
for($i=0;$i<count($array);$i ) {
<input id="postid" name="postid" type="hidden" value="$array[$i]; ?>"
}
If I click div post id (position 2) I get 20 if I click div post id position 3 I get 50
(function ($){
$(document).on('click','#postid',function(e){
e.preventDefault();
var postid=$('#postid').val();
console.log(postid);
});
})(jQuery);
CodePudding user response:
So you need to echo the input tag along with the Position
text. Also, it is a good practice to wrap the text node inside a parent tag for referring, like a div
. id
needs to be unique for each HTML element. In your case, having an id
or class
attribute is trivial anyways since the input type is hidden
.
So, better to add a class for the parent div
tag and output the text
on it's click listener.
Backend Snippet:
<?php
$array = array(15,20,50,23,10);
for($i = 0; $i < count($array); $i ) {
echo "<div class='post'><input name='postid_$array[$i]' type='hidden' value='$array[$i]' /> Position ".($i 1)."</div>";
}
Frontend Snippet:
(function ($){
$(document).on('click','.post',function(e){
console.log($(this).text());
});
})(jQuery);
CodePudding user response:
This should work for you.
PHP snippet
$array = array(15,20,50,23,10);
$i = 1;
foreach($array as $single_value){
echo "<div class='post'><input name='postid_".$i."' type='hidden' value='".$single_value."' /> Position ".$i."</div>";
$i ;
}
Front-end Javascript
(function ($){
$(document).on('click','.post',function(e){
console.log($(this).find('input').val());
});
})(jQuery);