Use php generated ids within jquery - php

I am pulling my id's from a database with a foreach loop in a html file using
<div id="<?php print ($schedule['boxA']); ?>">
The question is how to use id's generated this way in a jQuery script?
<script>
jQuery('I NEED TO INPUT ID HERE').datetimepicker({
datepicker:false,
format:'H:i',
step: 15,
});
</script>

I would (and do) use a different pattern. You don't need to use the ID to reference an element with jQuery, so you can add a datetimepicker widget more generically by using the class selector.
HTML (inside foreach loop):
<div class="timepicker" id="<?php echo $schedule['boxA']; ?>">
JavaScript (only once):
<script>
jQuery('.timepicker').datetimepicker({
datepicker:false,
format:'H:i',
step: 15,
});
</script>

You would use the generated id's the same way that you always do in jQuery.
jQuery('#generated_id') // replace 'generated_id' with the id supplied by PHP
If you are wanting to echo the id's you could do something like this when the page is being rendered -
jQuery("#<?php echo $schedule['boxA']; ?>").datetimepicker({

Bad idea.
I would suggest something like:
<div id="boxA" data-id="<?=$schedule['boxA']?>">
Or similar. The ID should be constant and known - that's what makes it an IDentifier. data-id can then be used to hold the server's ID reference to the thing in question.

Related

How to apply jQuery function to DOM elements with similar IDs?

I got this script:
<script>
$('#zoom_01').elevateZoom({});
</script>
Where #zoom_01 is an ID of an image. I have many images with ID's like so:
zoom_01
zoom_02
zoom_03
zoom_04
and so on
How do i make so that javascript would take all ID's instead of one?
I was thinking something like this:
<script>
<?php
foreach ($ArrayAllOfIDs as $i) {
$('#<?php echo $i; } ?>').elevateZoom({});
}
?>
</script>
But it didnt work.
Although using the class attribute as mentioned above is probably your best bet, if you are forced to work with the IDs for whatever reason You can use a "starts with" selector like
$("[id^=zoom_]").elevateZoom({})
which will apply elevateZoom to all DOM elements with an id that starts with "zoom_".
Add a class to all the images that would be affected at the same time.
Ids are used to identify a unique, non repeating item. Since your images are all pretty much the same, a class can group them together.
Then, change your javascript to select the class.
$('.zoom').elevateZoom({});
I don't know what elevateZoom is, but you can likely have this syntax:
$('#zoom_01, #zoom_02, #zoom_03, ...').elevateZoom({});
Make the PHP write out the Javascript so it is available when the page is loaded in the browser.
<script>
<?php
foreach ($ArrayAllOfIDs as $i) {
echo '$(\'#zoom_'. $i .'} \').elevateZoom({});\n';
}
?>
</script>

is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?
Consider this scenario -
<body id="body1">
Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -
<body id=" <?php echo $bodyID; ?> ">
I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.
thanks.
PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.
<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>
OR You can output all of the HTML using a single echo statement.
<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>
In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...
$(function() {
var variable = 'insert_id';
$('body').attr('id', variable);
});
gives (with jquery)
<body id="insert_id">
Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.
I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.
Edit: If you are only setting this on the body then you would not need to access it later.

Handling jQuery click events on divs produced in a foreach loop

I have an HTML div:
<div id='text_icon_<?php $i++; ?>' class="text_icon">Some Text</div>
that I print inside a foreach loop. I am using ajax to handle the click() event on it and change its text to Done!, so I have an output like:
<div class="text">Done!</div>
If I run the loop 4 times and I click on one of the divs (i.e. the one with class text_icon) then only first one is working while the rest of the divs are not working.
Update:
Your update indicates the below is not the problem, the IDs are unique.
Without your jQuery code it's hard to help you debug, so here's an example of how it can be done:
HTML:
<div id='text_icon1' class='text_icon'>Div #1</div>
<div id='text_icon2' class='text_icon'>Div #2</div>
<div id='text_icon3' class='text_icon'>Div #3</div>
<div id='text_icon4' class='text_icon'>Div #4</div>
JavaScript code using jQuery:
$("div.text_icon").click(function() {
// Within the `click` handler, `this` points to the
// DOM element. If you're kicking off some ajax something,
// you'll probably be doing something like this:
// Grab `this` to a variable we can access from the
// `success` closure
var theDiv = this;
// Do our call
$.ajax({
url: "your_url_here",
success: function() {
// It worked, udate the div
$(theDiv).text("Done!");
}
});
});
Live copy
Original answer:
If you're really using "DIV id='text_icon' class="text_icon..../DIV", e.g.:
<DIV id='text_icon' class="text_icon">....</DIV>
...then the problem is that the id is not unique. ID values must be unique on the page (reference). That would seem to fit with the symptom you describe, with "only the first one" working. Most browsers, when given invalid HTML with multiple IDs, will use the ID on the first element in document order and ignore the remaining ones.
If you don't need the div to have an ID at all, you can just remove it. Otherwise, just ensure the ID is unique, e.g.:
<DIV id='text_icon1' class="text_icon">....</DIV>
<DIV id='text_icon2' class="text_icon">....</DIV>
<DIV id='text_icon3' class="text_icon">....</DIV>
<DIV id='text_icon4' class="text_icon">....</DIV>
As far as I can tell, you are giving your divs the same ID. Targetting multiple elements with the same ID is impossible, the IDs need to be unique.
Try this:
$i = 1;
foreach ($array as $al) {
echo "<div id='text_icon_$i'>blablabla</div>";
$i++;
}
Of course, you'll need to modify your jQuery code too to include a potentially unlimited number of such IDs (I don't know whether performance will be good this way, but I remember doing it once for a comments list on a blog).
Another way would be to use a common class rather than unique IDs :).
Apart from the arguments about unique IDs, could it also be that the click handlers need to be hooked up again after the ajax call? If so, it'd be better to use .live rather than .click.
$("div.text_icon").live("click",
function(event) {
var icon = $(this);
}
}

jQuery, getting a value with a single class and multiple links

Here's the issue I'm running into. I have a list of names, if a name is clicked on, I need jQuery to pass the variable to another page.
This is what I have, but of course it only pulls the first name.
$('.nameLink').live('click', function() {
var coachName = $('.coachName').val();
$('#grayBorder').load('/team.php?coachName='+coachName);
});
And the php code that generates the coaches names:
while($row=mysql_fetch_assoc($query)){
echo '<a class="nameLink">
<input type="hidden" class="coachName" value="'.$row['coach'].'" />
'.$row['coach'].'
</a>';
}
Is there anyway to write this so that it will get the correct name?
Instead of $('.coachName') you should have $('.coachName', this)
Currently, you are searching the entire page for elements with class coachName, but you really only want to find element below the clicked element. By passing the jQuery function a context (in your case this), you tell it only to search within this scope.
Try:
var coachName = $(this).children('.coachName').val();

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories