Get the name of ONE element when it is clicked in PHP - php

I'm wondering how I can get the name of an element when it is clicked in PHP, but all elements have the same name for this instance...
PHP:
<?php
$playlist_names = array("Chill", "Groovy", "Pastasauce", "Dank Songs", "Katy Perry");
for ($i = 0; $i < count($playlist_names); $i++) {
echo "$playlist_names[$i]<img src=\"http://i.imgur.com/pLLny9D.png\" class=\"gear-icon\" />";
}
?>
What I'm trying to do is when "playlist-name" is clicked - It will return the playlist name in a different div with the text "Editing [Name of the playlist here]"
This does seem like a simple problem, but as always thanks for helping out!

Use $(this).text(); to get the text inside an html element
for your case to retrive only the first element text you can use this selector :
$("div p:nth-child(1)").text();
and so one for the other ones .

here is the link to Jquery's explanation of the on method, which is what you SHOULD be using. as well as the code and a JSfiddle for kicks.
//onclick of ANY <p> element with a class of .sample
$( "p" ).on( "click", ".sample", function() {
//do something
alert($( this ).text());
});

Related

expand/collapse div (toggle) when clicking on header

I have the following jQuery code to toggle the view of more information in a div.
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
});
The code works to toggle the view of displaying more information when the submission header is clicked. The div IDs of $moreInfo are dynamically created.
$moreInfo = $bidValue.''."_status";
echo "<div class='expandCollapse' id='$bidValue'>Submission</div>";
echo "<div id='$moreInfo'>$displayComments</div>";
However I want to open only one view/div at a time. If a div is open when a submission is clicked it should be closed before the other one is opened.
I've tried several things but it closes or hides all divs. Searching the web only show a solution using anchor tags.
Any thoughts...?
Thanks.
To achieve this you can put a common class on the second div element to allow you to hide them all before showing the next, like this:
echo '<div id="$moreInfo" class="expand-area">$displayComments</div>';
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#" + bidValue + '_status').slideToggle(500)
$('.expand-area').not(expandArea).hide();
});
Also note that you can make your code much more simple and generic by usnig DOM traversal to select the elements, instead of building selector strings based on related id attributes, like this:
$(".expandCollapse").click(function () {
var expandArea = $(this).next('.expand-area').slideToggle(500);
$('.expand-area').not(expandArea).hide();
});
The code above assumes that the elements are siblings, but you can easily amend the next() to traverse however is required.
Assuming the header and content divs are siblings you may use:
$(.expandCollapse + div)
// All <div>s that are immediately after an .expandCollapse
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
$('.expandCollapse + div').not(expandArea).hide();
});
$('[id$="_status"]').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='expandCollapse' id='bidValue1'>Submission1</div>
<div id='bidValue1_status'>displayComments</div>
<div class='expandCollapse' id='bidValue2'>Submission2</div>
<div id='bidValue2_status'>displayComments</div>
<div class='expandCollapse' id='bidValue3'>Submission3</div>
<div id='bidValue3_status'>displayComments</div>

get increasing variable from php to jquery

how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute

Select an element's id from PHP loop using jQuery

I have a list of <img> tags with each of them contains different id. This is done using PHP for loop as shown below:
<?php
for($n=0; $n<=5; $n++)
{
?>
<img id="<?php echo 'time_'.$n; ?>" src="$output-mp4_thumbnails-$n.jpg">
<?php
}
?>
I want to use jQuery in such a way that, when I click on the specific image on my browser, it would print out the id accordingly. Below is how I code it:
$(document).ready(function () {
$("img").click(function () {
alert($("img").attr("id"));
});
});
However this keeps printing only the first id, which is time_0. I have been looking around for ways to solve this, and I found out about change(), but it can only be used for form inputs.
Any suggestions will be greatly appreciated.
You're nesting php tags <?php and ?>, specifically in the loop.
Try to echo out the image tag as:
for($n=0; $n<=5; $n++)
{
echo "<img id='time_{$n}' src='{$output}-mp4_thumbnails-{$n}.jpg' />";
}
This should generate unique image ids as time_0, time_1 and so on upto time_5. In addition to this, you also need to incorporate either #Arun's answer or #tchow002 answer on the jQuery side as:
$(document).ready(function () {
$("img").click(function () {
alert(this.id)
});
});
Try this alert($(this).attr("id"));
this will select the img that was clicked. Your current code matches the first img instead and does not account for what was clicked.
you have a problem with the alert, you have alert($("img").attr("id")) which will always alert the id of the first img element, instead you need to alert the id of the clicked element so alert(this.id)
$(document).ready(function () {
$("img").click(function () {
var $id = this.id;
alert(id);
});
});
for($n=0; $n<=5; $n++) {
echo sprintf("<img id='time_%d' src='%s-mp4_thumbnails-%d.jpg' />", $n, $output, $n);
}

Applying jquery to elements echoed from php

EDIT: THE PROBLEMS WERE CAUSED BY AN IMPROPERLY LOADING JQUERY LIBRARY, AN ISSUE NOT SPELLED OUT CLEARLY IN MY ORIGINAL QUESTION. APOLOGIES.
I'm using jquery to hide, post, then echo the results of a php query to two separate divs. I then want to be able to swap the resulting images across these divs. The first part works fine, but I'm unable to get any other jquery scripts to work on these divs (e.g. sortable, droppable, etc).
I'm new to scripting within the past few weeks. I think I need to json encode the php stuff before I send it, but I'm having trouble finding clear guidance online about how to do this. Any help much appreciated, whether either descriptive, referral to specific intro resources (e.g. not php.net), or with code itself.
I am including relevant scripts below. This one works:
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$( "#search_results").show();
var search_val = $("#search_term").val();
var search_valb = $("#search_theme").val();
$.post( "./find.php", {search_term : search_val, search_theme : search_valb}, function(data){
if (data.length>0){
$( "#search_results").html(data);
$( ".portfolio_container").hide();
$( ".portfolio_draggables").hide();
$( "ul.clickable_container li").click(function(){
$( ".portfolio_draggables").hide();
var activeImage = $(this).find("a").attr('href');
$( ".portfolio_container").show();
$( activeImage).show();
return false;
});
};
});
};
</script>
This is the html form that I'm using.
<div id="lettersearchform" class = "lettersearchform">
<form id="searchform" method="post">
<label for="search_term">Enter your word here!</label>
<input type="text" name="search_term[]" id="search_term" />
<!--<input type="submit" value="search" id="search_button" />-->
</form>
</div>
<div id="search_results"></div>
The "search_results" are generated successfully with this script:
$alpharray = array();
while($row = mysqli_fetch_assoc($result)){
$alpharray[$row['letter']][] = $row;
}
$first = $second = array();
foreach( str_split( $_POST['search_term']) as $alpha)
{
$first[] = "<li><a href = '#$alpha'><img class='imgs_clickable_droppable' img src='../Letterproject/images/{$alpharray[$alpha][0]['photoPath']}' width='100' height='140'></src></a></li>";
$editable = array("<div id='$alpha' class='portfolio_draggables'>");
foreach ($alpharray[$alpha] as $tempvar)
{
$editable[] = "<a href ='findall.php'><img src='../Letterproject/images/{$tempvar['photoPath']}' width='70' height='110'></src></a>";
}
$editable[] = '</div>';
$second[] = implode( '', $editable);
}
echo '<ul id = "clickable" class="clickable_container">';
echo implode( '', $first);
echo '</ul>';
echo '<div id="portfolio" class = "portfolio_container">';
echo implode( '', $second);
echo '</div>';
So here's where the problem enters: This sortable script is more limited than the cross-div I want, but this type of thing won't work.
$(function() {
$("ul.clickable li").draggable({
containment: 'parent',
revert: 'invalid',
opacity: '0.91',
cursor: 'crosshair'
});
$('.clickable').sortable();
});
For those interested in more context, I'm using jquery to post the input from a form. A Php script matches the characters inputted to a corresponding letter image in a mysql db. It then echoes a list of these images to one div and echoes the whole portfolio of all images of that letter to another div. The idea is that a user could drag images from this second output to replace a letter image in the other div.
Thanks so much!
$("ul.clickable li")
does not correctly select an element with an HTML id of clickable and a class of clickable container. Either change the class of the element (which is selected with . in jQuery/CSS) or the id (which is selected with #)
$("#clickable")
should work.
Additionally, /src is unnecessary as src is not a tag. Writing out HTML directly in PHP script is not the cleanest way of doing this. I highly recommend you check out Head First HTML/CSS or HF HTML5 to augment some of your understanding.

Dynamic Selectors with Jquery with php while loop

I have a while loop which creates a list of anchor tags each with a unique class name counting from 1 to however many items there are. I would like to change a css attriubute on a specific anchor tag and class when it is clicked so lets say the background color is changed. Here is my code
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo "<a class='$i'>$title</a>
}
I would like my jquery to look something like this, it is obviously going to be more complicated than this I am just confused as where to start.
$(document).ready(function() {
$('a .1 .2 .3 .4 and so on').click(function() {
$('a ./*whichever class was clicked*/').css('background':'red');
});
});
Can you give the class a more consistent name? Like myClass_1, myClass_2, etc.
Then you could do:
$(document).ready(function() {
$('a[class^=myClass_]').click(function() { // Assign handler to elements with a
// class that starts with 'myClass_'
$(this).css('background','red'); // Change background of clicked one.
});
});
Here, a "starts with" selector is used to assign the event to all classes that start with myClass.
You could still retrieve the index number if needed.
Within the event handler, $(this) refers to the one that was clicked.
Live Example: http://jsfiddle.net/Jurv3/
Docs for "starts with" selector: http://api.jquery.com/attribute-starts-with-selector/
EDIT: I had a missing ] in the selector. Fixed now.
You can use an iterator over an array like this:
var myclasses = [".1",".2",".3"]; // generated by php
$.each(myclasses, function(index, value) {
$('a '+value).click(function() {
$(this).css('background':'red');
});
});
Note: I think you might be better off using unique ID for each item in your list of anchor tags and have them all share a single class. That's more what classes and IDs are for.
Just give them all the same class, say, myClass. Then:
$('a.myClass').click(function () {
$(this).css('background':'red');
});
This will work as long as you're having the links operate on themselves, or on their parents - as long as the relationship between link and target is the same for each. To operate on the parent, it would be $(this).parent().css(...), and to operate on the next element it would be $(this).next().css(...) and so on.
have you tried something like this?
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo '<a class="anchor_link" id="'.$i.'">'.$title.'</a>';
}
And then for the jQuery:
$(document).ready(function() {
$('a.anchor_link').click(function() {
var thisAnchor = $(this).attr('id');
$(this).css('background':'red');
});
});
The reason for my adding the js var 'thisAnchor' is because I am assuming that you need that $i php variable as the anchor marker? if so you can just take the js var and use it however you need. if you can't use ID because the anchored content is marked by id, use a diferent attr, such as 'title' or 'alt'.
I hope this was helpful.

Categories