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);
}
Related
I have the following PHP that returns records from a my MYSQL table. These records are displayed as LINKS. See code below...
<div class="slide1" id="u1026">
<?php while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental.php?id={$row['client_name']}\"></a>";
}?>
</div>
What I would like, is for the HREF link to change to
\"brochures\items-rental-layout2.php?id={$row['client_name']}\
If VALUE contains the text "layout2". I know that I can change HREF using jquery code
$(document).ready(function () {
$("#event").attr("href", "http://the.new.url")
});
I'm just not sure how to do that depending if the VALUE contains text "layout2". Any help is much appreciated. Thanks
You can just do it straight in the PHP code:
while ($row = mysql_fetch_array($query_rental)) {
$layoutFlag = $row['layout'] == 'layout2' ? '-layout2' : '';
echo "<a class='fancybox fancybox.iframe' id='rental' value=\"{$row['layout']}\" href=\"brochures\items-rental{$layoutFlag}.php?id={$row['client_name']}\"></a>";
}
You could also do it with Javascript:
$(function () {
// I'm assuming you are going to turn it into a rental class, otherwise change the selector to whatever.
$("a.rental").each(function() {
var rentalItem = $(this);
if (rentalItem.attr('value') === 'layout2') {
// You can choose what to replace, as long as you know it will replace EXACTLY what you want it to. I'm just going with Regex's ^ (start-of-line) operator to make sure that what we are replacing is at the start of the line...
rentalItem.attr('href', rentalItem.attr('href').replace(/^brochures\\items\-rental/, 'brochures\\items-rental-layout2'));
});
});
As you can see, just doing it in PHP is so much easier.
Also as a side note, you are creating multiple elements with the same id. Maybe you meant class='fancybox fancybox.iframe rental'?
And as a second side note, I suggest using the data- prefix for holding custom data. In layout's case, use data-layout='layout-whatever'. You can then use .attr('data-layout') to get the layout attribute (it's easier to understand what that code is doing too!).
You can either run the IF statement on the PHP loop
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
Or by jQuery
$( "a.fancybox" ).each(function( index ) {
if($(this).val() == "layout2") {
oldHref = $(this).attr('href');
newHref = oldHref.replace('items-rental.php', 'items-rental-layout2.php')
$(this).attr('href', newHref);
}
});
all your links have the same ID which can cause some issues when you wuold want to work with them with jQuery.
If you have more a tags with the fancybox class, try adding a unique class to these tags and update the each loop
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());
});
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
I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com
i am using while loop to output data in
<p><?php echo $title;?></p></font></a><button id=show>show()</button> <button id=hide>hide()</button>
my show hide function is
$("#show").click(function () {
$("p").show('fast');
});
$("#hide").click(function () {
$("p").hide('fast');
});
$("#reset").click(function(){
location.reload();
});
now when i am clicking show hide only the first show hide loop is working and it shows/hides all the data not just the one i clicked
Change the code to use this, like so:
$(this).prev('p').show('fast');
You will need to do this in each JQuery .click section.
Edit:
Another good point which has been mentioned, you are using an ID for your element which won't allow this to work on more than one. Your new markup should look like:
<p><?php echo $title;?></p></font></a><button class="show">show()</button>
and the JQuery:
$(".show").click(function () {
$(this).prev('p').show('fast');
});
Welcome to SO. Nice to see that you have formated your first question nicely.
Few things you might want to change.
As you are going through a loop, make sure you use a counter inside the loop and add the counter to the id. This will make the id a unique identifier. Also wrap them inside a div.
$counter = 0;
forloop {
$counter++;
<div>
<p><?php echo $title;?></p></font></a><button id="show<?php echo $counter; ?>">show()</button>
</div>
}
So now your id will be unique.
Now you can write your jquery in the below way.
$("button").click(function () {
$(this).attr('id'); //not required but incase you need the id of the button which was clicked.
$(this).parent().find("p").show('fast');
});
$("button").click(function () {
$(this).parent().find("p").hide('fast');
});
Two things: 1. I think you can only have one element with one id, such as #show. If you want to reference more buttons, you should use a class, such as this: show() (as I understand the buttons are output in a loop, there will be more of them).
Second: inside your javascript code, you do $("p")... - this references all elements on the page. I think you should use $(this) and start from there, check out this article, it explains a lot: http://remysharp.com/2007/04/12/jquerys-this-demystified/
There are many ways to go at this. Here's one:
First, add the loop number to the IDs (let's say it's $i)
<p id="TITLE_<?php echo $i; ?>" style="display:none;"><?php echo $title;?></p>
<input type="button" class="show" data-number="<?php echo $i; ?>"/>
<input type="button" class="hide" data-number="<?php echo $i; ?>" />
Your functions will then be:
$(".show").click(function () {
$("TITLE_" + $(this).data('number')).show('fast');
});
$(".hide").click(function () {
$("TITLE_" + $(this).data('number')).hide('fast');
});
Of course there are ways to do it via JQUERY without the use of the $i.
Edit: To have the tags hidden on page load, either use the style=display:none as I have added in the tag above, or you can use JQuery as follows:
$(document).ready( function() {
$("p[id^=TITLE_]").hide();
// this will retrieve all <p> tags with ID that starts
// with TITLE_ and hide them
});