Separate function for buttons created dynamically - php

I print this buttons with php taking info from the BBDD:
print "
<div class='col-sm-6 col-md-6 col-lg-3 col-xl-3 cartasdos'>
<figure><img class='imagenEditar' height='190px' width='100%' src='../img/relatos/".$fila['imagen']."'></figure>
<h3>".$fila['titulo']."</h3>
<h5>".$fila['autor']."</h5>
<h6 class='resumen'> ".$fila['sinopsis']." </h6>
<a href='index.php?id=".$fila['id']."' class='btn btn-info' role='button'>Editar</a>
<input type='button' class='btn btn-danger borrar ' value='Borrar'>
<a href='crud.php?id=".$fila['id']."' class='btn btn-danger si' role='button'>Borrar</a>
<input type='button' class='btn btn-black cancelar' value='Cancelar'>
</div>";
And then with jquery I want hide and show the buttons separated but when I press one of the buttons it affect to all. This is the jQuery:
<script>
$(document).ready(function(){
$(".si").hide();
$(".cancelar").hide();
var botones=document.querySelectorAll(".borrar");
for(i=0;i<botones.length;i++){
botones[i].addEventListener("click",cancelar,false);
}
});
function cancelar(e){
$(".si").toggle();
$(".cancelar").toggle();
$(e.target).toggle();
$(".cancelar").on("click", function(){
$(".borrar").show();
$(".si").hide();
$(".cancelar").hide();
});
}
</script>
How could I do it?

You can toggle each button with the click() on the selector and toggle() on your button e.g.:
$("selector").click(function(){
$(".yourtBtn").toggle();
});

You want to use $(this) to isolate which item you want to act on. This is an example of the difference:
https://jsfiddle.net/dto07w65/1/
In your case, it might be something like:
<script>
$(function() {
// When you click on any elements with this class
$(".cancelar").on("click", function(){
e.preventDefault();
// Get the parent that wraps this particular clicked element
var parent = $(this).parents('.cartasdos');
// Once selected, show just this element
parent.find(".borrar").show();
// Hide all the others
parent.find(".si").hide();
parent.find(".cancelar").hide();
});
});
</script>
I am not 100% how you want your buttons to work, but his shows how to isolate using $(this).

I finally solve it with an incremented $id, inside of the bucle that print the buttons y write the $id in the principal button and in the rest of buttons I put it in the class:
$id=0;
while($fila=mysqli_fetch_array($res)){
$id++;
print "
<div class='col-sm-6 col-md-6 col-lg-3 col-xl-3 cartasdos'>
<figure><img class='imagenEditar' height='190px' width='100%' src='../img/relatos/".$fila['imagen']."'></figure>
<h3>".$fila['titulo']."</h3>
<h5>".$fila['autor']."</h5>
<h6 class='resumen'> ".$fila['sinopsis']." </h6>
<a href='index.php?id=".$fila['id']."' class='btn btn-info' role='button'>Editar</a>
<input type='button' class='btn btn-danger borrar' id='".$id."' value='Borrar'>
<p class='seguro ".$id."'>Ana, ¿Estás segura?</p>
<a href='crud.php?id=".$fila['id']."' class='btn btn-danger si ".$id."' role='button'>Borrar</a>
<input type='button' class='btn btn-black cancelar ".$id."' value='Cancelar'>
</div>
";
}
And in the jquery code I take the e.target.id for the buttons with the $id in the class and e.target for the principal button with the $id in the id:
<script>
$(document).ready(function(){
$(".seguro").hide();
$(".si").hide();
$(".cancelar").hide();
var botones=document.querySelectorAll(".borrar");
for(i=0;i<botones.length;i++){
botones[i].addEventListener("click",cancelar,false);
}
});
function cancelar(e){
$("."+e.target.id).slideDown('slow');
$(e.target).slideUp('slow');
$(".cancelar").on("click", function(){
$(e.target).slideDown('slow');
$("."+e.target.id).slideUp('slow');
});
}
</script>

Related

Change class toggle to multiple span element with Jquery

I need to change the class of a span child that uses a toggle when I click on one of the browser rows.
But it only works when there is a single row, when there are several rows it does not find the span and it does not work.
I also tried to use the href to select the correct span, but I don't know how to use it in the JQuery code
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#01" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#02" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
jQuery(function($) {
$('#menu-toggle').on('click', function() {
var $el = $(this),
textNode = this.lastChild;
var $href = $(this).attr('href');
var $href = $href.substring(1);
$el.find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
});```
Try this
var el = 2
for(var i=0; i<el.length; i++) {
document.getElementsByClassName("glyphicon").find('span').toggleClass('glyphicon-
chevron-down glyphicon-chevron-up');
}
Finally I simplified the code so I commented the span and then call with the function onclick CambiaClass, using a class data1, data 2 ... dataN (to identify the item) and now is working fine.
Thanks for your help Rahul!!!
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#<?php echo $id_item; ?>"
class='btn btn-default glyphicon glyphicon-chevron-down <?php echo 'dato'.$id_item; ?>'
title='Ver pagos' onclick="CambiaClass('<?php echo 'dato'.$id_item; ?>')">
<!-- span class="glyphicon glyphicon-chevron-down"></span -->
</a>
//Jquery
<script type="text/javascript">
function CambiaClass(idclass) {
$("[class*='"+ idclass+"']").toggleClass('glyphicon glyphicon-chevron-down').toggleClass('glyphicon glyphicon-chevron-up');
}
</script>

Popover stops working after refreshing div?

I have anchor tags that when clicked, create popovers. After clicking a button in the popover, an ajax call is made which updates a database. The popover disappears and the div containing the popover anchor tags is refreshed. Following the div refresh, the anchor tags no longer display the popovers when clicked and when an anchor tag is hovered, it displays a title equal to the popover title. What is causing the popover not to work after a div refresh?
div that gets refreshed
<div class="content" id="content">
<div class="row">
<div class="col-3 heading">A</div>
<div class="col-3 heading">B</div>
</div>
<div class="row">
<a href="#" class="col-3 data
edit" data-toggle="popover" data-trigger:'click' data-html="true"
data-placement="top" title=""
data-content="
<div id='error'></div>
<form id='editForm'>
<input type='number' maxlength='5'class='form-control'
name='newAmount' id='newAmount'
value=''placeholder='New Amount'>
<br>
<input type='hidden' value='Car/Auto' name='catName'id='catName'>
<input type='submit' class='btn btn-primary btnPopover form-
control' value='Change'id='btnEdit' name='btnEdit'>
<a class='btn btn-warning btnPopover form-control'
id='btnCancelEdit'>Cancel</a>
</form>"
data-original-title="<div class='popoverTitle'>Edit </div>">
$900</a>
<div class="col-3 data">$500</div>
</div>
</div>
jquery to originally initialize popovers
$(function () {
loadPopovers();
})
function loadPopovers() {
$('[data-toggle="popover"]').popover();
$('.edit').click(function(){
$(this).popover('show');
$('[data-toggle="popover"]').not(this).popover('hide');
});
}
jquery ajax for div refresh
$(document).on('click','#btnEdit',function(e){
e.preventDefault();
var newAmount = $('#newAmount').val();
if(newAmount.length == 0){
document.getElementById("error").innerHTML = "<span
class='error'>Type a new amount or click cancel.</span>";
}else {
$.ajax({
type: 'post',
url: 'edit.php',
dataType: "json",
data: $('form').serialize(),
success: function (response) {
if(response.status === 'success'){
//Refresh div data
$.get("dataRefresh.php", {},
function (returnedHtml) {
$("#content").html(returnedHtml);
});
$('[data-toggle="popover"]').popover('hide');
loadPopovers();
}
}
});
}
});
Change
//Refresh div data
$.get("dataRefresh.php", function (returnedHtml) {
$("#content").html(returnedHtml);
});
$('[data-toggle="popover"]').popover('hide');
loadPopovers();
To
//Refresh div data
$.get("dataRefresh.php", function (returnedHtml) {
$("#content").html(returnedHtml);
$('[data-toggle="popover"]').popover('hide');
loadPopovers();
});
If you are going to use direct bindings, you have to run them after the data is rebuilt.

Modal inside PHP while loop with delete and edit only returns the ticket of the 1st row

I am displaying tickets and used while loop to display each on a table. Edit button is working fine for each loop however for the delete button I can't seem to pass the value of the ticket that I specifically want to delete. Function goes like this once the delete button is clicked it will go to a modal for confirmation of deletion but it always deletes the 1st row. I need to get the specific value of the ticket to pass to deleteconfirm.php Below is the code that I have used.
$stats = $_REQUEST['stats'];
$query20 ="SELECT * FROM user WHERE status='$stats' ORDER BY date_received
DESC";
$result2 = mysqli_query($datalog,$query20);
while( $row = mysqli_fetch_assoc( $result2 ) ){
if($row['task5']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'].'/'.$row['task3'].'/'.$row['task4'].'/'.$row['task5'];
}
elseif($row['task4']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'].'/'.$row['task3'].'/'.$row['task4'];
}
elseif($row['task3']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'].'/'.$row['task3'];
}
elseif($row['task2']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'];
}
elseif($row['task1']!=''){
$tasks = $row['task'].'/'.$row['task1'];
}
elseif($row['task']!=''){
$tasks = $row['task'];
}
echo
"<tr>
<td>{$row['ticket']}</td>
<td>{$row['date_received']}</td>
<td>{$row['subject']}</td>
<td>{$row['property']}</td>
<td>$tasks</td>
<td>{$row['territory']}</td>
<td>{$row['loadername']}</td>
<td>{$row['seniorname']}</td>
<td>{$row['qaname']}</td>
<td><a href=editticket.php?supe=".$row['ticket']." target='_top'>
<span class='glyphicon glyphicon-edit'></span></a>
<button class='open-homeEvents' id='btnPopModal' href='#' data-
toggle='modal' data-target='#confirmdelete' data-
id=".$row['ticket']." > <span class='glyphicon glyphicon-trash'
style='color:red'></span></button>";
echo"
<div class='modal fade' id='confirmdelete' role='dialog'>
<form method='POST' action='deleteconfirm.php' id='delcon' >
<div class='form-group'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal'>×
</button>
<h4 class='modal-title'>Confirm Delete</h4>
</div>
<div class='modal-body'>
<p>Are you sure you want to Delete Ticket <b> <input
type='hidden' name='eventId' id='eventId'/>
<span id='idHolder' name='idHolder'></span>
</b>?</p>
<p>If Yes please confirm indicating reason below:</p>
<p><textarea id='res' name='res' required></textarea></p>
<input hidden id='delc' name='delc' value=".$row['ticket']."
/>
</div>
<div class='modal-footer'>
<button class='btn btn-default' href='#' type='submit'
target='_parent'>Yes</button>
<button type='button' class='btn btn-default' data-
dismiss='modal'>No</button>
</div>
</div>
</div>
</div>
</div>
</form>
</td>
</tr>\n";} ?>
Below is the code for deleteconfirm.php
<?php
session_start();
require_once('datalog.php');
$delc=$_POST['delc'];
$tak= $_POST['tak'];
$res=$_POST['res'];
if(isset($_REQUEST['delc'])&&$_REQUEST['delc']!=''
&&isset($_SESSION['SESS_USER_NAME'])){
$tickets=$delc;
$delid=$_SESSION['SESS_USER_NAME'];
$query22="SELECT * from memberinfo WHERE username='$delid'";
$result22=mysqli_query($datalog,$query22);
while( $row1 = mysqli_fetch_assoc( $result22 ) ){
$delby=$row1['full_name'];
}
$query23="SELECT * from user WHERE ticket='$delc'";
$result23=mysqli_query($datalog,$query23);
while( $row = mysqli_fetch_assoc( $result23 ) ){
$subject= $row['subject'];
$property= $row['property'];
$country= $row['country'];
$city= $row['city'];
$validity= $row['validity'];
$remarks= $row['remarks'];
$priority= $row['tagging'];
$territory= $row['territory'];
$status= $row['status'];
$date_received= $row['date_received'];
$loader= $row['loadername'];
$senior= $row['seniorname'];
$qa= $row['qaname'];
}
$query1="INSERT INTO deletehistory (iddeleted_by,deleted_by,deletereason,subject,property,task,country,city,validity,remarks,ticket,priority,status,date_received,loader,qa,senior,territory) values ('".$delid."','".$delby."','".$res."','".$subject."','".$property."','".$tak."','".$country."','".$city."','".$validity."','".$remarks."','".$delc."','".$priority."','".$status."','".$date_received."','".$loader."','".$qa."','".$senior."','".$territory."')";
$result1=mysqli_query($datalog,$query1);
}
$query4="DELETE FROM user WHERE ticket='$delc' ";
$result4=mysqli_query($datalog,$query4);
header("location: delete.php");
?>
Hope someone can enlighten me on this one, Thanks in advance!
You can use data-whatever in the button tag of delete e.g here
<button class='open-homeEvents' id='btnPopModal' href='#' data-
toggle='modal' data-target='#confirmdelete' data-
whatever="$row['ticket']" >
And use a jquery js to get the data in the modal
<script type="text/javascript">
$('#confirmdelete').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('#eventId').val(recipient);
})
</script>

jquery/Ajax get value of data-id from a text link

I have A VERY OLD SCRIPT that I need to modify. You will notice from the code it is using mysql_query() which is outdataed however that is not my issue.
I have a text link in a file named surveycommentslist.php. The link opens a jquery model window that I need to capture a user inputed text in and then save it to a mysql along with the value of the links data-id which tells me which unique user ID to connect the comment to. My issue is I am not able to get the value of data-id using the code I have below.
Here is my code
<html>
<head>
<!-- common scripts -->
<!-- jQuery library -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.js"></script>
<!-- jQuery migrate -->
<script src="js/jquery-migrate-1.2.1.min.js"></script>
<!-- bootstrap framework plugins -->
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<script>
$(document).on('click', '.reply', function()
{
//get acommentuid
var val = $(this).attr('data-id');
$.post('surveycommentslist.php', {acommentuid: val}, function(data)
{
console.log(data);
});
});
</script>
<?php
//lets list comments
$scommentsql = mysql_query("SELECT * FROM survey_comments
WHERE surveyid=$surveyid ORDER BY commentdate asc");
while($scrows = mysql_fetch_array($scommentsql))
{
extract($scrows);
$the_comment = stripslashes($the_comment);
$commentdate = date("m/d/Y h:ia", strtotime($commentdate));
if($touid > 0) { $indent = "margin-left:35px"; }
//get name of person making the comment
$nsql = mysql_query("SELECT fname, lname, userlevel, id AS scommentid FROM users WHERE id=$uid LIMIT 1");
$namerow = mysql_fetch_array($nsql);
$commenters_fname = stripslashes($namerow['fname']);
$commenters_lname = stripslashes($namerow['lname']);
if($namerow['userlevel'] > 19)
{
$adminicon = "<img src='./img/admin_smicon.png' alt='admin'>";
}
echo "<div class='ch-message-item clearfix' style='$indent'>
<div class='ch-content'>
$the_comment
</div>
<p class='ch-name'>
<strong>$adminicon $commenters_fname $commenters_lname</strong>
<span class='muted'>$commentdate</span>";
if($touid == 0)
{
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
}
echo "</p>
</div>";
}
$(document).on('click', '.reply', function(e)
{
e.preventDefault();
//get acommentuid
var val = $(this).data('id');
$.post('surveycommentslist.php', {acommentuid: val}, function(data)
{
console.log(data);
});
});
Class attribute is not closed properly. Quotes issue.
Change this
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
to
echo "<a href='#switch_modal' class='reply btn btn-default' id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
Maybe there's just an issue with the single and double quote in the REPLY. You said $scommentid has a value, so I assume there's just an echo problem. Try these:
//codes
.
.
//RE-POSITION class values from id value
echo "<a href='#switch_modal' class='reply btn btn-default btn-small' id='$scommentid' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
//or by concatenation if I am wrong with the above solution
echo "<a href='#switch_modal' class='reply btn btn-default id=".'"$scommentid"'." btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
//or by using the " if I am wrong with the above solutions
echo "<a href='#switch_modal' class='reply btn btn-default id="$scommentid" btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
.
.
//codes
When I copy-paste your code in a file & execute that in a browser, it shows the "data-id" attribute as blank: http://screencast.com/t/pasXI14dp0x . That is due to the incorrect HTML pointed out in earlier messages.
Even after the corrections, there is still the 'btn-small' text which is not in any attribute.
The incorrect HTML is:
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
The correct HTML should be:
echo " <a href='#switch_modal' class='reply btn btn-default btn-small' id='$scommentid' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
Another alternative you could try is hardcode some value in the "data-id" attribute & find out if it's being passed. If that works, then the issue is with the HTML & should be fixed with above corrected HTML code.
Your HTML markup is wrong
You can check that by doing a view source
Change the following code
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
with
echo "<a href='#switch_modal' class='reply btn btn-default btn-small' id='$scommentid' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
I would suggest to you to return the data from MySQL as JSON using return json_encode($data) which $data is an array of key-value pairs and when you get the data in your script tag / JavaScript, just build the HTML there and add it to a div instead of returning HTML from the server.
When you build your HTML in your script tag / JavaScript, you add the data from the JSON response and loop over the comments.
Maybe that's just me but I like clean code :)

Can I create anchorpoints to the list of elements my PHP-function gets?

I'm fairly new to coding, but have managed to create a function that gets all my elements in the database and echos them out in a list. However, I want each element to have an individual anchorpoint so that i can use the "#" in my link to refer to a specific element.
My whole function currently looks like this (Please excuse some strange names as they're in norwegian):
function visAktiveForslagFlestStemmer()
{
echo "<section id='innhold'><h2>Aktive forslag</h2>";
$db = returnerDB();
if(!$db)
{
die("Kunne ikke knytte til databasen");
}
$sql = "SELECT Tittel, Tekst, COUNT(stemme.ForslagID) AS Antall FROM forslag, stemme WHERE stemme.ForslagID = forslag.ForslagID AND forslag.Aktiv = 1 AND forslag.Besvart IS NULL GROUP BY stemme.ForslagID ORDER BY Antall DESC";
$resultat = $db->query($sql);
$i=1;
$index=1;
while ($rad = mysqli_fetch_array($resultat, MYSQLI_ASSOC))
{
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('#beskrivelse".$index."').hide();
$('#visSkjulButton".$index."').click(function(){
$('#beskrivelse".$index."').toggle(500, 'swing');
});
});
</script>";
if ($i%2==0)
{
$tall="repeteres";
$ftall="forslag";
$sstall="stemmeOgSosialt";
$stall="stemme";
$sotall="sosialt";
}
else
{
$tall="repeteres2";
$ftall="forslag2";
$sstall="stemmeOgSosialt2";
$stall="stemme2";
$sotall="sosialt2";
}
echo "<a id='anchor".$i."'><div class='".$tall."'><div class='".$ftall."'><p><h3>".$rad["Tittel"]."</h3></p><div id='beskrivelse".$index."'>
<p id='forslagbeskrivelse'>".$rad["Tekst"]."</p></div><button class='btn btn-info' id='visSkjulButton".$index."'>Vis/ Skjul</button></div><div class='".$sstall."'><div class='".$stall."'>
<p><div class='btn btn-primary btn-lg center-block disabled'>".antallStemmer($rad["ForslagID"])."</div></p>
<br><br><div class='btn btn-primary btn-lg center-block'>Avgi Stemme</div></div>
<div class='".$sotall."'><a href='http://facebook.com' class='image1'></a><a href='http://twitter.com' class='image2'></a><a href='http://plus.google.com' class='image3'></a>
<div class='btn btn-warning btn-md' id='rapporterButton'>Rapportér</div></div></div></a>";
$i++;
$index++;
}
mysqli_close($db);
This function is called in a separate page, which is included in my index.php-page. My index.php-page also includes a navigation bar, assigning [mywebpage.com/index.php]?page=1 to the end of the url where the function is being called.
The issue I'm having is that adding for example "#anchor1" to this link does not make my browser window jump to the first (or any) element that this function gets from the database.
Can anyone please pont to where my error lies?
In case anyone else has issues wit this, the simple solution was to echo this:
echo "<a id='forslag".$rad["ForslagID"]."'><div class='".$tall."'></a><div class='".$ftall."'><p><h3>".$rad["Tittel"]."</a></h3></p><div id='beskrivelse".$index."'>
<p id='forslagbeskrivelse'>".$rad["Tekst"]."</p></div><button class='btn btn-info' id='visSkjulButton".$index."'>Vis/ Skjul</button></div><div class='".$sstall."'><div class='".$stall."'>
<p><div class='btn btn-primary btn-lg center-block disabled'>".antallStemmer($rad["ForslagID"])."</div></p>
<br><br><div class='btn btn-primary btn-lg center-block'>Avgi Stemme</div></div>
<div class='".$sotall."'>
<a href='https://www.facebook.com/sharer/sharer.php?u=localhost/TestM/index.php?page=1#forslag".$rad["ForslagID"]."' target='_blank' class='image1'></a>
<a href='https://twitter.com/home?status=St%C3%B8tt%20forslaget%20til%20NHHS%20her%3A%20http%3A//localhost/TestM/index.php?page=1%23".$rad["ForslagID"]."' target='_blank' class='image2'></a>
<a href='https://plus.google.com/share?url=nhhs.no' target='_blank' class='image3'></a>
<div class='btn btn-warning btn-md' id='rapporterButton'>Rapportér</button></div></div></div>";
In other words to just surround my first <div> with the anchor point.

Categories