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.
Related
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>
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());
});
My question is simple.
I have the following code:
<div class="last"
<?php
if hasClass(last){
echo " style='width:100%;' ";
}
?>
></div>
I know the if statement is wrong, but the idea is there. I want to know how can I check if this div has the .last class then echo something.
I've been searching around but didn't work anything (didn't find much though).
Best regards.
As already in the comments told it's possible with PHP with DOM parsers.
I'm gonna give you 2 very simple solutions which will save you a lot of work:
CSS:
<style>
.last {
width:100%;
}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
if($('div').hasClass('last')){
$('div').css('width', '100%');
}
});
</script>
PHP runs on server, so it generates HTML. If you have that class="last" you don't need to check - it's part of the code....hard-coded.
But you can have some PHP variable and depending on it's place print out class and also style for that other element:
<?php
$print_last = true;
?>
...
<div <?php if ($print_last) echo 'class="last" ';
<?php
if ($print_last){
echo " style='width:100%;' ";
}
?>
></div>
But if you want to check on html element you have to do it on client side (browser) from JavaScript and jQuery can be helpful too.
It is possible to check that using PHP, however that couldn't be done easliy (you'll need to parse buffered HTML using DOM parser, then look up for divs, etc...).... Much better solution is to do that with Javascript/jQuery, using Document.getElementsByClassName() function.
Sample solution:
var elements = document.getElementsByClassName("last");
for(var i = 0; i < elements.length; i++)
{
var element = elements[i];
element.style.width = "100%";
}
#azhpo
Obviously the HTML being the front end language you have to pass the elements either through some submit button or via ajax request.
Using submit button: select the class name of div using either javascript
var className = document.getElementById("myDIV").className
document.getElementById("myHiddenField").value = className;
Now on clicking the submit button it would get submitted
Using ajax:
Again take the classname either through javascript / jquery
var className = jQuery("#myDiv").attr("class");
Now fire ajax query and send the class name to your script
jQuery.ajax({
url: 'file.php',
type: 'POST',
data: 'class='+className,
success: function(data){//do whatever you want},
error:function(){//do whatever you want}
});
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 some SQL output that id like to format into a collapsible div. The problem is that all the JS show/hide div code I find isn't really meant for dynamic instances, they all need to be pre-assigned to a particular div. Since my results may vary from 1-30...this isn't really a good option.
My question. Is there an easy way to dynamically generate show/hide controls for a varying number of layers?
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="0">Tab</div>
<div class="CollapsiblePanelContent">Content</div>
</div>
<script type="text/javascript">
<!--
var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel1");
//-->
</script>
It actually is pretty easy with mootools (or jquery for that matter).
You just need to give all generated divs the same class and select all of them and apply collapsible behaviour.
This is a little script written in mootools for one of our projects and might get you on the way. It fetches all elements with classes that start with toggle_ and the part that comes after the underscore is the id of the div this control is supposed to collapse.
So you generate a butteon with class 'toggle_mydiv1' which would toggle a div with id 'mydiv1'
This way you can generate as many elements as you want and assign behaviour to all of them with one script.
Written in mootools:
window.addEvent('domready', function(){
var clickAbles = $$('form[class^=toggle_]');
clickAbles.each(function(el){
var _class = el.get('class').split(' ');
var clickElement = _class[0].replace('toggle_','');
clickElement = $$('ul.buttons li.'+clickElement+' a');
if(clickElement){
var myFx = new Fx.Tween(el,{duration: 'long'});
var myFx2 = new Fx.Tween(el,{duration: 'long'});
el.store('height', el.getSize().y);
el.store('state', 'close');
el.setStyles({'display': 'none', 'height': 0});
var todoLists = el.getElements('ul.todo_list');
clickElement.addEvent('click', function(e){
e.stop();
if(el.retrieve('state') == "close"){
el.setStyle('display','block');
myFx.start('height', [0,el.retrieve('height')]);
myFx.addEvent('complete', function(){
todoLists.setStyles({'overflow': 'auto'});
el.store('state', 'open');
});
} else {
if(el.retrieve('state') == "open"){
myFx2.start('height', [el.retrieve('height'),0]);
myFx2.addEvent('complete', function(){
el.setStyles({'display': 'none', 'height': 0});
todoLists.setStyles({'overflow': 'hidden'});
el.store('state', 'close');
});
}
}
});
}
});
});