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>
Related
I'm creating a social media site with php & mysqli. On the index page all post are loaded using a while loop and on the profile page that specific users post are loaded the same way. I have the like button hooked to ajax so you can like without refresh but it only works on the latest post.
The inside the while loop I have include('post.php') and this is what is in there.
<div class="post_options" id="post_options">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
</div>
<script>
const button = document.querySelector(".post_options .like<?php echo $row['id'] ?>")
button.onclick = () => {
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid=<?php echo $row['id'] ?>", true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>
What i understand from your code is that your script is outside the while loop. Hence it is taking the last value from your loop as the $row variable will store latest value.
You can add data attribute to your post div and then get that value on button click
<div class="post_options" id="post_options" data-id="<?php echo $row['id'] ?>">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
<script>
const button = document.querySelector(".post_options")
button.onclick = () => {
var contentid = $(this).data('id');
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid="+contentid, true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>
Hi guys i got a problem with my Code. I load new Page Content on click of Button and got a JQuery Function with onclick which changes a love or like count on Page. If i dont include the JQuery Function into the Ajax loaded page it doesn`t work but if i do he acts twice the function any idea how to fix this or solutions?
This is the JQuery Script from page:
$(".toggle").on("click", function(e) {
$('.alert-box').hide();
$( '.alert-box' ).remove();
var $this = $(this);
var $lovecount = $this.closest("div").find(".lovecount");
if ($(e.target).hasClass('love')) {
//alert('Liebe genommen');
var val = +$lovecount.text() + (this.checked ? -1 : -1);
$(e.target).prop( "checked", false );
} else {
//alert('Liebe gegeben');
var val = +$lovecount.text() + (this.checked ? 1 : 1);
$(e.target).prop( "checked", true );
};
//var val = +$lovecount.text() + (this.checked ? 1 : -1);
$lovecount.text(val)
$('.alert-box').toggle(!this.checked);
$(this).toggleClass("love");
var postid = $this.attr("data-post");
var userid = $this.attr("data-userid");
dataString = 'userid=' + userid + '&postid=' + postid;
// Are you not supposed to send the new value to the server?
$.ajax({
type: 'POST',
url: 'inc/give-love.php',
data: dataString,
success: function(response) {
$('<div class="alert-box success">'+response+'</div>').prependTo('body').delay(3000).fadeOut(1000, function() {
$('.alert-box').hide();
$( '.alert-box' ).remove();
});
}
})
})
with this i change and toggle input from this HTML Code Structure.
<!-- POST ITEM START -->
<div class="post-item">
<div class="post-asset image">
<img src="uploads/<?php echo $row['picture']; ?>">
</div>
<div class="post-header">
<h3 class="post-title"><?php echo $row['title']; ?></h3>
<span class="post-category">
<a class="favorite-button" href="#" data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>"><span class="favorite-button-icon fa fa-star-o"></span></a>
</span>
<span class="post-date font17"><i class="fa fa-clock-o"></i> <?php $timeago=get_timeago(strtotime($row['created'])); echo $timeago;?></span>
<span class="post-comments font17"><i class="fa fa-comments-o"></i> 1,3k Reaktionen</span>
</div>
<div class="post-footer">
<a href="#" class="post-author">
<span class="author-img"><img src="img/avatar.png"></span>
<span class="author-name">OnePost von<b><?php echo $row['poster']; ?></b></span>
</a>
<div class="post-extra">
<!--<div class="add-favorite" id="heart-container"><span class="lovecount">112</span><input data-post="123" data-user="Jessica Jones" type="checkbox" id="toggle" onclick="myFunction(this)" checked><div id="twitter-heart" class=""></div></input></div>-->
<div class="add-favorite" id="heart-container"><span class="lovecount"><?php echo $row['loves']; ?></span>
<!--<input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle love" onclick="myFunction(this)">-->
<?php
if($row['is_liked'] != 1){ ?>
<input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle">
<?}else{?>
<input data-post="<?php echo $row['id']; ?>" data-userid="<?php echo $_SESSION['user_id'];?>" type="checkbox" id="toggle" class="toggle love" checked="true">
<?php }?>
<div id="twitter-heart" class=""></div></input></div>
<div class="post-share"><i class="fa fa-share-alt"></i>
<div class="social-links">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-whatsapp"></i>
</div>
</div>
</div>
</div>
</div>
<!-- POST ITEM END -->
When i include the JQuery script in Ajax page it fires twice the function if not onclick is not working. How to prevent this or make it working the right way?
If you append any element after DOM has loaded, you need to use delegate(); selector.
$(document).ready(function(){
$("#div1").append('<button id="btn">Click</button>');
//You can use delegate() selector and when you click #btn its works.
$("body").delegate("#btn", "click", function(){
alert("Button has working!");
});
});
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>
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 :)
Hello guys I'm trying to delete a record/row from my table using a modal delete confirmation. This is what I've tried so far:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
</script>
<table class="table table-bordered">
<?php
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
<tr>
<td><a href="project-detail.php?code=<?php echo $project; ?>">
<?php echo $project; ?></a></td>
<td><?php echo $desc; ?></td>
<td><a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white">
</i>
</a></td>
<td><a href="#<?php echo $project; ?>"
id="<?php echo $project; ?>"
data-id="<?php echo $project; ?>"
class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i></a></td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
</table>
But the problem is, when I am about to delete the last row the one that gets deleted is the first row. Why is it like that? Any ideas? Help is much appreciated. Thanks.
The problem lies in the modal generation and passing the $project value.
You are using a loop as
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
And inside the above loop you are generating the modals so basically you will have many modals which are equal to the num of rows in the query.
Now all of them are having the same "id" i.e. "dialog-example" and once you click on the delete it pop ups the first modal from the DOM and is deleting wrong data.
Solution
For each modal you give the id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the blow code
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
Get the id of the element using attr("id") and append this at the end of
"dialog-example_"+{id you received}
The same thing you need to do for the hide modal as well.
UPDATE ON HOW TO DO IT
Give the modal div id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the click function to as
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
Change
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
to
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="<?php echo $project ;?>">Yes<a>
AND finally
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
to
$(".btn btn-danger").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('hide');
});
because you generate modal for every row this is wrong !
and show modal(first modal show) this is wrong!(this delete first row)
create one modal and set parameter with jquery e.g
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
$("#dialog-example #btn-delete").attr('href','delete-project.php?code='+$(this).attr('data-id'));
});
good luck
On topic
Problem is you have multiple modals. But select it on 1 id. So jQuery will select the first value.
A solution would be to put the delete url in an hidden input field. Then when the user clicks the open delete modal you select the url and put it in the a tag.
Example time
JavaScript Part
$(function(){
$(".btn-show-modal").click(function(e){
// put the right url in the delete
$("#dialog-example .delete-url").attr('href', $(this).attr('data-delete-url');
$("#dialog-example").modal('show');
return e.preventDefault();
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
PHP part
I assume $stmt is prepared etc
<ul>
<? foreach($stmt->fetchAll() as $record) : ?>
<li>
delete
</li>
<? endforeach; ?>
</ul>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a class="delete-url btn btn-danger">Yes<a>
</div>
</div>
Code explaind
It is not handy to put an bootstrap modal in an foreach/for/while unless you change the id. But then again lot of duplicate code.
What the code does it changes the delete-url on the fly depending on which a the user clicked
Off topic
I highly recommend using the foreach for your iteration of the data records instead of a for loop.
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){ /** code **/}
would be
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
foreach($stmt2->fetchAll() as $record){}
Because when you open the modal, it open the first #dialog-example div.
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$(this).parent().find("#dialog-example").modal('show');
});