jQuery not extracting text values clicked properly - javascript

I am using a php script to extract values from the database as follows,
<div class="col-md-4" >
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while ($output = mysqli_fetch_array($rslt)) {
?>
<li class="nav" id="test" style= "text-decoration: none;">
<a href="postad" >
<?php echo $output['Classify'].'<br/>'; } ?>
</a>
</li>
</div>
<div class="col-md-4" id="testing">
</div>
this code gives me below result:
General equipment
Test equipment
Renewable energy
Engineering Services
Trade services
Below is the jQuery bit:
<script>
$(document).ready(function(){
$("#test").click(function(){
var classprod = $(this).text();
$("#testing").text(classprod);
event.preventDefault();
})
});
</script>
However this only outputs line-1 but nothing else i.e. General equipment.
What changes do I have to make to my javascript code in order to be able to display any item clicked?

Little errors, but easy to solve. Your php loop leave a lot of tags opened, an closes just one, then you should use a Class instead on an Id for multiple elements.
Another tip is that you should open and close the ul tag before your list.
HTML
<div class="col-md-4" >
<ul>
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while($output = mysqli_fetch_array($rslt)){?>
<li class="nav test" style= "text-decoration: none;"><a href="postad" ><?php echo $output['Classify'];?></a></li>
<?php };?>
</ul>
</div>
<div class="col-md-4" id="testing"></div>
JS
<script>
$(document).ready(function(){
$(".test").on('click',function(event){
event.preventDefault();
var classprod = $(this).text();
$("#testing").text(classprod);
})
});
</script>
Also, I don't know what you're doing, but consider to use $(".test a") instead of $(".test")

In General, id of HTML elements should be unique, this requirements can be realized when using jQuery or JavaScript. In your code, you used id="test" for the li element inside a loop, and then you referenced to them using $("#test") then, only first li works due to uniqueness of id.
you can use class instead of id.

Related

Results in words with space don't show in php gallery

I'm creating a gallery in php, where it has a filter divided into categories. But when a word has a space it doesn't show the associated images.
I'm working on two tables, one that creates the categories and the other that is from the gallery.
This is my code and the sql queries:
Querys:
$sql = "selec categoria AS categoria_formatted from cat_lar";
$galerialar = $connect->query($sql);
$sql = "select foto,categoria_lar from galeria_lar,cat_lar Where categoria_lar=categoria";
$galerialarconde = $connect->query($sql);
Code:
<div class="popular page_section">
<div class="container">
<div class="row">
<div align="center">
<button class="filter-button" data-filter="all">All</button>
<?php mysqli_data_seek($galerialar, 0);
while( $galerialarc = $galerialar -> fetch_assoc()){ ?>
<button class="filter-button" data-filter="<?php echo $galerialarc['categoria_formatted']?>"><?php echo $galerialarc['categoria_formatted']?></button>
<?php } ?>
</div>
<br/>
<?php
while( $galerialarc = $galerialarconde -> fetch_assoc()){ ?>
<div class="gallery_product col-sm-3 col-xs-6 filter <?php echo $galerialarc['categoria_lar']?>">
<a class="fancybox" rel="ligthbox" href="admin/galeria/uploads/<?php echo $galerialarc['foto']?>">
<img class="img-responsive" alt="" src="admin/galeria/uploads/<?php echo $galerialarc['foto']?>" width="150px" />
</a>
</div>
<?php }?>
</div>
</div>
</div>
SCRIPT:
<script>
$(document).ready(function(){
$(".filter-button").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
$('.filter').show('1000');
}
else
{
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
if ($(".filter-button").removeClass("active")) {
$(this).removeClass("active");
}
$(this).addClass("active");
});
});
/* end gallery */
$(document).ready(function(){
$(".fancybox").fancybox({
openEffect: "none",
closeEffect: "none"
});
});
</script>
Can they help me? Because I've already tried to put the words with "_" and replace and it remained the same
As you suggest yourself, the image URLs can't contain whitespaces. If you already tried to replace whitespaces with underscores (_) , remember to upload the image files with that name and replace the foto url in the database with the new images.
If it doesn't work, try to investigate where exactly the problem occurs. Is the queries returning the right results (try to var_dump() the result and see if they are missing. If you think the problem happends in the HTML, try using your "inspect" feature in your browser and see if a source URL is provided for the image element and check if this URL really has an image.

After generating divs using php for loop and also dynamically assigning for them ids how to i target the ids using jquery?

Am using a while loop to out various elements each containing rows from a mysql database. I was able to make each div have different id however, i have no idea how i can target each of the divs usings jquery through the ids so that each div is a clickable link.
Here is a part of my code
<!-- php script -->
<?php
require_once 'controllers/fetchVids.php';
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$fileName = $row[$filePath];
$file = basename($fileName);
$mb = round($row[$size] / (1000000), 2);
echo "
<div class='container search-output' id=''>
<div class='row song-info' id='file-$row[$videoId]'>
<div class= 'col col-sm-6 artist'>
$file
</div>
<div class= 'col col-sm-3 song-title'>
<span>Size:</span>
$mb mb
</div>
<div class= 'col col-sm-3 song-title'>
<span>Downloads:</span>
$row[$downloads]
</div>
</div>
<div class='row-lower'>
<a href='#' class='icon all-links'>
<i class='fa fa-whatsapp'></i> Share
</a>
<i class='fa fa-clock duration'></i> Duration $row[$duration] mins
</div>
</div>
";
} else {
echo "No New Videos";
}
mysqli_close($connection);
?>
Someone please show me the right jquery to do the above. thank you
Below is the jquery code i tried but it rather opens all the divs and not only that that a user clicks on
$(document).on('click', '.song-info', function() {
// alert(this.id);
if (this.id) {
window.location = "./song-details.php";
}
});
I think you were going wrong by using the 'this' keyword - you may have wanted to use $(this) instead, which is a keyword in jQuery that gives the DOM node you are currently working on access to jQuery methods (at least as far as I understand it!)
You can use $(this).attr('attribute name') (another jQuery method) to get the 'id' property of the div you clicked and use it within your function.
There are more than a few ways to do this, as mentioned in the comments, but here is how I would go about it. I'm assuming you want to send the fileId in a query string to './song-details.php'.
$(document).on('click', '.song-info', function() {
let id = $(this).attr('id').split('-').pop()
if (id) {
window.location = "./song-details.php" + "?id=" + id
}
})

Getting variable passed from PHP to JS on Click event, returns all elements variable, not just the one that's clicked

I'm working on a WP code, but my problem in specific to JS. So I post my question here at StackOverflow.
Final goal is, clicking on the post image, showing the HTML markup of large img on Console. Here's my code:
<div class="img lightbox-trigger">
<?php the_post_thumbnail(); ?>
<div class="hover" >
<i class="fa fa-arrows-alt"></i>
</div><!--hover-->
</div><!-- .img .lightbox-trigger -->
<?php $large_thumb = get_the_post_thumbnail($post->ID, 'large') ?>
<script type="text/javascript">
jQuery(document).ready(function($){
$(".lightbox-trigger").click(function(){
var largeThumb = <?php echo json_encode( $large_thumb ); ?>;
console.log( largeThumb );
});
});
</script>
The problem is when I click on one of the post's images, the largeThumb value of all other posts (there are 10 posts) printed on Console!
I don't know how to use $(this) in this specific context to just get the value related to the element being clicked on.
Any help is appreciated.
You could use data-* attributes to store the $large_thumb of every lightbox-trigger in the related div :
<div class="img lightbox-trigger" data-large-thumb='<?php echo get_the_post_thumbnail($post->ID, 'large'); ?>'>
<?php the_post_thumbnail(); ?>
<div class="hover" >
<i class="fa fa-arrows-alt"></i>
</div><!--hover-->
</div><!-- .img .lightbox-trigger -->
Then in the js you could get this info :
jQuery(document).ready(function($){
$(".lightbox-trigger").click(function(){
console.log( $(this).data('large-thumb') );
console.log( $(this).html() );
});
});
Hope this helps.

Jquery Clone only the clicked elements contents

I have this issue which I'm sure I have solved before but cant for the life of me figure it out again. What I want to happen is one someone clicks a blend tile it clones that tile's featured image into the mixes area which it does but it kindly takes every other image with it. I only want it to grab the clicked elements img nothing more.
My loop does add numeric values to the blend tiles num-<?php echo $i++; ?>
So even a working solution where it grabs that unique class could work for the clone.
Update
In order for it not to continually add the image to the repeated .color-img it will have to grab the class and inject it into <li> then also some how add it into the appendTo so that when the item is clicked it only ever add's it to the newly created box.
$(function() {
$(".blend-tile").click(function() {
$("#mixer ul.mixers").append('<li><div class="align-table"><div class="color-img t-align"></div><div class="t-align"><div class="percent-mix"></div></div><div class="t-align"><div class="mix-value"></div></div></div></li>'), slideumus();
$(".blend-tile .tpic").clone(true, true).contents().appendTo('.color-img');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- wordpress Loop -->
<li class="blend-tile align num-<?php echo $i++; ?>">
<div class="tpic">
<?php the_post_thumbnail( 'thumb-blend' ); ?>
</div>
<section class="infora">
<h2>
<?php the_title(); ?>
</h2>
<p class="price">
<span class="amount">
£
<?php
$available_variations = $product->get_available_variations();
$variation_id = $available_variations[0]['variation_id'];
$variable_product1 = new WC_Product_Variation( $variation_id );
$regular_price = $variable_product1 ->regular_price;
echo $regular_price;?>
</span>
</p>
</section>
</li>
<!-- end of wordpress Loop -->
<div id="mixer" class="t-align">
<ul class="mixers"></ul>
</div>
You can try this:
$(".tpic", this).clone(true, true).contents().appendTo('.color-img');
Because if you do
$(".blend-tile .tpic").clone(true, true).contents().appendTo('.color-img');
It will clone .tpic into your web page.
Well you are not selecting the one that was clicked, you have a selector inside that is selecting all the elements. You can get the one that was clicked by using this and you can get the elements inside with find.
$(".blend-tile .tpic").clone...
needs to be
$(this).find(".tpic").clone...
and if you have multiple .color-img' your code is also going to fail as it will append to every one of those elements. If you want to only to append to the one that was created, than you are going to have to keep a reference to the one that was just added.
var li = $('<li><div class="align-table"><div class="color-img t-align"></div><div class="t-align"><div class="percent-mix"></div></div><div class="t-align"><div class="mix-value"></div></div></div></li>');
$("#mixer ul.mixers").append(li);
slideumus(); //no clue hy this was there with a comma
$(this).find(".tpic").clone(true, true).contents().appendTo(li.find('.color-img'));

jQuery show and hide dynamic classes not working

I am trying to hide and show div's displayed on my page with a select element however having a bit of trouble as I can't seem to get the jQuery to function.
I am listing results from my SQL table using PHP that currently displays every row onto my page and prints them into a list.
I want to make the jQuery hide the div's that don't have a class that matches the select option that is selected.
Here is an example of the listing template that echo's out all of the MySQL results and displays them into a template and is then looped to display every row on the table:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container ' . $row["Make"] . '">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
The 'Make' is added to the listing-container div to add a class to be able to filter the results with jQuery.
Here is the form with the select element I am using:
<form>
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option>'.$make["Make"].'</option>
';
} ?>
</select>
<select class="form-control last-select select-box">
<option value="model-any">Model (Any)</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
</form>
As you can see the select option contains the 'Make' and is looped.
So down to the jQuery:
<script>//Wait for DOM to load
(function() {
$(“.select-box”).change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(“.listing-container”).not(“.” + make).hide();
});
});</script>
So in theory this should work but for some reason it isn't, can anybody notice anything that might be wrong?
I have placed my script below the core jQuery in my footer and it still doesn't work.
Here is a live example: http://www.drivencarsales.co.uk/used-cars.php
Looks like you're using the wrong quotes in the source code of that page try replacing them with "
//Wait for DOM to load
$(function() {
$(".select-box").change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(".listing-container").not("." + make).hide().next().hide();
});
});
Edit
You also need a $ before the function
If I understand you correctly ↓ working code ↓
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('div.listing-container.'+make+",div.listing-container."+make+" + div.listing-container-spec").show();
$('div.listing-container:not(.'+make+'),div.listing-container:not(.'+make+') + div.listing-container-spec').hide();
});
});
And shorter code (but slower):
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('.listing-container.'+make+",.listing-container."+make+" + div").show();
$('.listing-container:not(.'+make+'),.listing-container:not(.'+make+') + div').hide();
});
});
P.S.You miss value attribute (but in live example everything ok):
echo '<option value="'.$make["Make"].'">'.$make["Make"].'</option>';

Categories

Resources