Get array number by position - javascript

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);

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);
Online Output UI demo

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);

Related

How to show/hide a div independently among others with the same class name within a loop

i have a while loop within an SQL query that returns all comments for a specific post page , within that same loop i have another query and a while loop that searches for replies to that comment and returns only the first row using LIMIT 1. I did this so only one reply is shown for a comment at first, i added another another query and a loop within the second loop to search for other replies to the comment except this time I'm returning the other rows except the first row using LIMIT 1,18446744073709551615. I've put the result of the last query in a div which is hidden at first, and a trigger view all replies in the first query which comes before the hidden div.
So now i have a trigger view all replies inside the first loop (that contains the comments). using javascript i can show and hide the div when the trigger is clicked. this is a snapshot of what it looks like
First snapshot, div is hidden with only 1 reply being shown.
second snapshot, div is visible and text for trigger is changed
My problem:
Since I'm using the same class for all hidden div's, the trigger for a particular comment to show/hide its replies works for all comments. so when i click on view all replies for the first comment, the replies for the second,third etc are shown as well. How do rewrite my code to target specific comments to show/hide its replies?
JavaScript
<html>
<head>
<script language="JavaScript">
$(document).ready(function(){
var showText='View all replies';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links
$('.view1').prev().append();
$(".licom").hide();
$(".view1").click(function(){
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
$('.licom').toggle(function() {
$(this).closest('view1').find('.licom').hide();
return false;
},
function() {
$(this).closest("view1").next(".licom").show();
return false;
});
});
});
</script>
</head>
<body>
</body>
</html>
info.php
<?php
...........
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
while($obj = $stmt->fetch()){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id1 = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
//trigger to hide/show replies
echo '<span class="view1" style="float:right;margin-top:-15px;">View all replies</span>';
//
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
//Relpy to comment, show only the first row
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
//...........same output as first without the view all replies trigger......
//Relpy to comment, show from 2-
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1,18446744073709551615");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
//div to show/hide
echo '<div class="licom">';
//...........same output as first without the view all replies trigger......
}
}
}
?>
$('.licom').toggle()... is too broad and will select all elements with the 'licom' class, regardless of whether or not they were inside of the element that was clicked. Try $(this).children('.licom') instead.
Since you already have a unique comment ID, you could add that as an ID attribute to your comment-container element, similar to this:
echo '<div class="comment-container" id="comment-' . $id . '">';
Then, your jQuery for toggling the comments (only within that container) would look something like this:
//When a user clicks "View all replies"...
$('.view1').click(function() {
//Find the ID of the comment container he/she clicked inside
var commentID = $(this).closest('.comment-container').attr('id');
//Use that ID to make the selector more specific when targeting the reply elements
$('#' + commentID + ' .licom').toggle();
});
In other words, your jQuery/CSS selector just needs to be more specific.
Also, if you want to add a little bit of (subtle) animation to the show/hide behavior, jQuery's toggle() function accepts several options for accomplishing this: http://api.jquery.com/toggle/
UPDATE
I just realized that your .licom elements are not inside the .comment-container element like I originally assumed. So here's a modified version of my answer that allows you to keep your existing HTML structure.
In addition to outputting the comment ID as the id attribute on the .comment-container (that first line of PHP in my original answer), you also need to output it as a class on each .licom, like this:
echo '<div class="licom comment-' . $id . '">';
Then, the jQuery looks like this:
//When a user clicks "View all replies"...
$('.view1').click(function() {
//Find the ID of the comment container he/she clicked inside
var commentID = $(this).closest('.comment-container').attr('id');
//Use that ID to make the selector more specific when targeting the reply elements
$('.licom.' + commentID).toggle();
});
i've changed my triggers to be unique
echo'View all replies';
and my div class to show/hide to be unique as well by group.
echo '<div class="licom licom-'.$cc_id.'">';//$cc_id has the same value as trigger. example $id1=2, $cc_id=2.
now i have the trigger as licom-1 and div to show/hide as licom licom-1
then i changed my javascript to:
<script language="JavaScript">
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
var id = $(this).attr('id');
if($('.'+id).css('display') == 'none')
{
$('.'+id).css('display','block');
}
else
{
$('.'+id).css('display','none');
}
return false; // cancel original event to prevent form submitting
})
})
</script>
This javascript would only show/hide the div with same licom value i.e only the replies with same id would be toggled by that trigger.
and lastly to make all licom hidden, i added the css.
.licom {
display:none;
}

PHP: print from a list of data (loop difficult)

Hi i have a little problem,my code create a list of buttons and each button have a name(value) from my list (table 'usernames')
....for exemple (table 'usernames' have 3 lines aa-bb-cc my code make 3 button with values aa & bb & cc..............
so what i want to do, is when i click on a button i want to print the value of this button in a div, for exemple if i click on the button who have the value 2 i want to print 2 in the div(i have a problem whit my loop, and i need help please)
this is my code:
$conn=mysqli_connect("localhost", "root", "pwd","sn") or die(mysqli_error());
$que2=mysqli_query($conn,"select usernames from posts", MYSQLI_USE_RESULT); // return a lot of lines on 'usernames'
$re=0;
$datax=array();
$i=0;
while ($r = mysqli_fetch_array($que2))
{
$re = $r["cnt"];
$datax[$i]=$re;
?>
<input id="ppost" name="ppost" value="<?php echo $datax[$i]; ?>" type="submit">
<br>
<script type="text/javascript">
$(function(){
$('#ppost').click(function(){
alert("<?php echo $datax[$i]; ?>");
});
});
</script>
<?php
$i++;
}
Ok, so there're few things to have a look at:
take the <script> out of the loop - one script can take care of all the buttons
you can't give same ID to all your inputs - id="..." has to be unique throughout your script
the JS script (assuming you have jQuery included prior to your ) should be:
<script type="text/javascript">
$(function(){
$('input[type="submit"]').click(function(){
alert($(this).attr('value'));
});
});
</script>
this should do the trick, let me know if this is what you wanted.

how to get text of div in php variable while its text come from js function

Here is my modal code
<p id="getdatevalue" style="display:none;"></p> //HOW TO GET THIS DIV TEXT IN PHP
</div>
I am getting date of php in this anchor tag
<?php
for($i = 1; $i <= $this->daysInCurrentMonth + $this->firstDayOfTheWeek; $i++) {
?>SetRecipe
<?php
$day++;
}
?>
and opening modal window on click of this link
I am passing date as id in some div and getting same id when click on testclass , mean i am getting value of date suppose 27-04-2014 in id populated via lope
<script>
$(".testclass").click(function(event) {
var date_value = $(this).attr("id");
$("#getdatevalue").html(date_value);
});
</script>
using jquery post
<script>
$(".testclass").click(function(event) {
var date_value = $(this).attr("id");
$("#getdatevalue").html(date_value);
$.post('aPhpFile.php',{
dateVal: $("#getdatevalue").html()
});
// since you specifically asked how to get the value from that
// element, but $.post('aPhpFile.php',{dateVal:date_value});
// would be fine
});
</script>
and php (aPhpFile.php);
<?php
$postedVal = $_POST['dateVal'];

javascript display and hide div element

I am new to Javascript, and I currently have an article that is being fetched from database, the article has two rows. title & content there are about 100 of these in my database. Now the objective is to list all the titles first, and when a user clicks on a title, to make the the relevant content appear underneath it. I can do this however this way.
<?php
//mysql query here...
foreach($result as $row) { ?>
<div id='title'> <?= $row['title'] ?> </div>
<div id='<?= $row['id'] ?>' style='display:none'
onclick=showContent(<?= $row['id'] ?>) > <?= $row['content'] ?>
</div>
<?php } ?>
The javascript to hide the show the content is this:
<script type='text/javascript'>
function showContent(id){
document.getElementById(id).style.display='inline';
}
</script>
The showContent() function hides the div based on the id passed through the paramenter.
But, the only problem is that, I need other previously displayed divs to truntate when a new one opens.
Meaning, the content should be visible only once, then when you click on another title, the previously opened content should disappear and only the new content should appear.
I hope that made sense. as I am lacking the grammar to explain it all. I tried to give small example here, which for some reason does not seem to work at all, but does in my localhost http://jsfiddle.net/YL6aH/
EDITED:
My full PHP loop, together will all the js/html
<?php
$articlesForPreview = $createQuery
->query("SELECT * FROM timeline");
$fetchAll = $articlesForPreview->fetchAll(PDO::FETCH_ASSOC);
foreach($fetchAll as $row) {?>
<div id='timeline_container'>
<span class='timeline_date'> <?= $row['time'] ?></span>
<span class='timeline_title'> <a href='#' onclick=timeline(<?= $row['id'] ?>)><?= $row['title'] ?></a></span>
<p id='<?= $row['id'] ?>' style='display:none;'> <?= $row['event'] ?></a></span>
</div>
<?php }?>
</aside>
</section>
<script type='text/javascript'>
function timeline(id){
document.getElementById(id).style.display='inline';
}
</script>
<footer id='footer_container'>
You can simply remember the last item that is visible:
var active;
function showContent(id){
if (active) active.style.display = 'none'; // hide previously visible element
active = document.getElementById(id); // keep track of the element you are about to show
active.style.display='inline'; // show the new element
}
Keep in mind that this solution starts with no items visible and after that only allows one item to be visible at a time.
You should try this :
function showContent(id){
$('.active').hide().removeClass('active');
$('#'+id).show().addClass('active');
}
I see also that you will have multiple elements with id=title, you must change it to make every elem unique.
You can go through all elements with an onclick of "showContent", hide them all, afterwards you can just show the one you want.
function showContent(id){
var allElements = document.getElementsByTagName('*');
for ( var i = 0; i<allElements.length; i++ ) {
if ( (allElements[i].onclick + "").indexOf("showContent") >= 0) {
allElements[i].style.display = "none";
}
}
document.getElementById(id).style.display='inline';
}
I'm pretty new to javascript and jquery myself, but one of the things we just did in the class I'm taking was the accordion display, where you attach event handlers in the document.ready for the click events for the header objects, and their div children elements, and it was done by swapping the css classes on the click events... are you using css? in our version, anytime we clicked on a plus, it would expand the display to display the divs below, and clicking the minus pic it would close them... ours did it for all of them, but you should be able to code that even to "close" all of those displays, and then open/display only the divs that are children for the item clicked... is that what you're looking for?

Execute a Javascript function from a button in a table row cell which was generated by PHP echo

I want to call a Javascript function from a table row cell.
I need to pass the id of that row as well.
In one cell I use an href (which does popup my edit dialog), but does not pass the Id (BrId).
The next one, well ideally a button which invokes a Javascript function (though I've seen code/functions which associates a click event function within $(document).ready(function() {.....etc}) but unsure if this will pick up the required Id (BrId) which is a primary key to a database table.
Code is:
foreach ($myrows as $row) {
echo "<tr>";
echo '<td style="border:none;">' .$row->BrId. '</td>';
echo '......'
echo '......'
echo '<td style="border:none;"><a href="#dialog" name="modal">Edit this branch </td>';
echo '<td style="border:none;"><button onclick="EditBranch (1)"></td>';
}
Ideally the function would also show my popup div ( id= dialog ) as the "a href="#dialog" name="modal" does.
If this helps, here's a section of the script:
$(document).ready(function() {
//select all the a tags with name equal to modal
$('a[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var id = $(this).attr('href'); //gets me my div id
//other code for transition effects and positioning of my div....
}
You can pass the row id through a custom html data attribute :
echo ' Edit this branch ';
Then, you simply retrieve it like that :
var id = $(this).attr('data-id');

Categories

Resources