Arraylist not working in php - php
i have created a arraylist in php
It is place in a button . When i click on it opens the button, it opens all the aaraylist but there is some problem with the code the link to,the code is here.can someone tell me where is the problem.
var Arraylist<String> = new Arraylist<String>;
The problem is that any click will immediately hide the dropdown, after which you make it visible again by toggling it.
I'm trying to edit you fiddle to try and get it to work the way you want :).
Edit: here is a fiddle that does what I think you want it to do: fiddle
The idea I got from your fiddle is that you want to toggle the menu when you click it, and if you click anywhere else, the menu is hidden by default.
This works by remembering if the item was toggled or not, if not, it'll hide by default.
var nav = $('#nav');
nav.find('ul#nav').toggle();
var emp = $(this);
$("html").click(function() {});
$(document).bind('click', function(e) {
var dd = $("ul.dropdown");
var toggled = false;
var target = $(e.target); //2
if (target.parent().is('#nav')) {
var li = target.closest('li.menu');
toggled = true;
li.find('ul.dropdown').toggle();
}
if (!toggled) {
dd.hide();
}
});
OK, let's tackle all the problems with your code.
I'll explain what you're doing wrong and why, and what is recommended.
First up:
HTML Markup.
Your included example code contains markup errors. You're closing one of your list items inside the nested unordered list after the nested unordered list. Minor, but yet important for valid markup. Some browsers can go nuts over these things.
The second thing I noticed was that you're using the same ID for the lists. An ID is unique to the document in order to quickly reference it in CSS and Javascript. If you intend to select more than one element in the document, use classes, that's what they're there for. You can read more about it here or here.
Depending on what intended use you have for it; to achieve the same desired result, consider using this markup instead
<div class='emp_alt'>
<div class='container'>
<div class='title'>EMP</div>
<img src="http://www.iconarchive.com/download/i32215/tpdkdesign.net/refresh-cl/Symbols-Find.ico">
</div>
<div class='dropdown'>Contact no.</div>
</div>
Generally speaking, it requires less processing time for the client the less elements you have. When you apply CSS to the elements it is highly recommended to select them by class or ID, not by tag name. Using tag names can take up extra processing time because the client has to do more generalized searches. You can read more about efficient CSS here.
Here's a working example with your corrected markup.
Here's a working example using the alternate markup.
I'm not sure if you're trying to accomplish a sort of tooltip behavior, in which case, this example should suit you.
The JQuery (Javascript)
The other answers rightly pointed out your main problem was that you were hiding the dropdown on click. What they didn't address was that when the user clicks on something, and your document click picks up on it, it's going to return the element that is in the front.
So, when you click on the text, the #nav element is in the front. The image however, is an element in its own, and is in front of the #nav element.
This is why you should use the proper events instead because they include everything inside the element.
As you may have noticed in my examples above, there is a faster, cleaner and better way of achieving what you want.
You should be doing something like this instead
var dropdowns = $(".dropdown");
$(".nav > li").click(function(e){
//Prevent document click event from firing
e.stopPropagation();
var this_dropdown = $(this).children("ul.dropdown");
dropdowns.not(this_dropdown).hide();
this_dropdown.toggle();
});
//Hide all dropdowns if not clicked on a list item (or container)
$(document).click(function(){
dropdowns.hide();
});
Note: if you don't want to stop propagation you can use a "sensor" instead. Basically, a sensor determines a boolean's state which is then used to determine if the document click event should do anything or not. An if statement checking the boolean's state at document click should suffice.
var dropdowns = $(".dropdown");
var sensor_state = true;
$(".nav > li").click(function(e){
var this_dropdown = $(this).children("ul.dropdown");
dropdowns.not(this_dropdown).hide();
this_dropdown.toggle();
}).mouseenter(function(){
sensor_state = false;
}).mouseleave(function(){
sensor_state = true;
});
$(document).click(function(){
if(sensor_state){
dropdowns.hide();
}
});
This relies on the markup where the nav element has a dropdown child.
Here's an example using your example.
The problem here is that your markup makes this code toggle the dropdown when it itself is clicked. That's why I added a container to the earlier examples.
Hopefully, I've made at least some sense and cleared up your problem.
Update
After your latest comments, indicating you're using jqgrid and you want a dropdown inside, I decided to create a rather thorough example of how it can be done.
I suggest you study the code and learn from it. You don't have to do exactly as I did, as long as you know how and why.
Functionality:
When a user clicks a contact cell in the jqgrid it will show the dropdown container and the data provided from the "server" (custom array data is easier than staging an ajax event). The data provided by the server is in a hidden column (following the contact column)
If you click inside the dropdown container, it will not close. I added a close button inside it because users might otherwise get confused as to how to close it. It's better to have one than not to have one
If you click anywhere else in the document, it will close
If the user clicks the same cell while the dropdown container is visible, it will close
The dropdown container is not attached to the cell itself, but is instead positioned from the outside. This allows us to reuse the same container, instead of creating new containers for every single cell, saving us time in the process.
This is as far as writing your code I'm willing to go. The rest is up to you mate :)
I am reluctant to add more text to this post, but for completeness sake, I will add the entirety of the example code.
Code | JSFiddle Example
HTML
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/redmond/jquery-ui-custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/ui.multiselect.css" />
<script src="http://trirand.com/blog/jqgrid/js/jquery.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery-ui-custom.min.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery.layout.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/ui.multiselect.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery.tablednd.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery.contextmenu.js" type="text/javascript"></script>
<table id="list"></table>
<div id="pager"></div>
<div id="contact_info"></div>
CSS
#contact_info{
position: absolute;
top: 0;
left: 0;
display:none;
background-color: white;
border: 1px solid gray;
padding: 5px 3px;
-moz-box-shadow: 3px 3px 4px #CCC;
-webkit-box-shadow: 3px 3px 4px #CCC;
box-shadow: 3px 3px 4px #CCC;
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#CCCCCC')";
}
#list .contact{
cursor: pointer;
}
.container{
cursor: pointer;
}
td.contact:active{
background-color: #FBEC88;
}
.container .dropdown{
display: none;
}
.ui-jqgrid tr.jqgrow td{
white-space: normal;
}
/*
Style the dropdown box
*/
h2{
border-bottom: 1px solid lightgray;
}
p{
padding: 2px;
}
h2, p{
margin: 0;
}
.close_btn{
font-size: 10px;
line-height: 10px;
float: right;
text-decoration: none;
}
Javascript
//Preload the image to avoid flashes
search_img= new Image();
search_img.src = "http://www.iconarchive.com/download/i32215/tpdkdesign.net/refresh-cl/Symbols-Find.ico";
//The dropdown container
var contact_info = $("#contact_info");
//ID of last clicked row
var last_row;
//Sensor state determining whether document click will close the dropdown container on click
var sensor_state = true;
//Dropdown information data (base)
var dd_bp = "<img src='"+search_img.src+"'>",
dd_inf = "<h2>Contact information</h2><p>Phone: 555-12345<br/>E-mail: something#someplace.whatever<br/>P/O Box: 555555</p>"
//Data array (don't know what you use as a source, but I'll keep it simple)
//This setup allows you to send dropdown data from the server as well :)
var data_from_server = [
{id:"1",title:"Economy advisor",name:"Luke",lname:"North", contact: dd_bp, dropdown: dd_inf},
{id:"2",title:"Salesperson",name:"John",lname:"Smith",contact: dd_bp, dropdown: dd_inf},
{id:"3",title:"Economy advisor",name:"Jimmy",lname:"Hendrix",contact: dd_bp, dropdown: dd_inf},
{id:"6",title:"IT Manager",name:"Caroline",lname:"GlaDos",contact: dd_bp, dropdown: dd_inf},
{id:"5",title:"Quality Inspector",name:"Paul",lname:"Shoreman",contact: dd_bp, dropdown: dd_inf},
{id:"4",title:"Quality Inspector",name:"Liza",lname:"Ingridge",contact: dd_bp, dropdown: dd_inf},
{id:"8",title:"Distribution manager",name:"Elisabeth",lname:"Welman",contact: dd_bp, dropdown: dd_inf},
{id:"10",title:"Quality Inspector",name:"John",lname:"Johansson",contact: dd_bp, dropdown: dd_inf},
{id:"11",title:"Economy advisor",name:"Tommy",lname:"the Knuckle",contact: dd_bp, dropdown: dd_inf},
{id:"9",title:"Manufacturer",name:"Rosa",lname:"Minx",contact: dd_bp, dropdown: dd_inf}
];
//Adds the content to and repositions the dropdown container to the current row cell
function show_contact_info(rowid){
var row = $("#"+rowid),
contact_cell = $("td.contact", row),
dropdown_content = $("td.dropdown", row).html();
//Add the content
contact_info.html(dropdown_content).append("<a class='close_btn' href='#'>close</a>");
//Add a close button event
$(".close_btn").on("click", function(e){
e.preventDefault();
contact_info.hide();
});
//Position the contact info box
contact_info.css({
//The last calculations will center the container
left: contact_cell.offset().left - contact_info.outerWidth()/2 + contact_cell.outerWidth()/2,
//The last calculation will position the container below the cell, replace it with
// -contact_info.outerHeight() to position it above the cell
top: contact_cell.offset().top + contact_cell.outerHeight(),
});
contact_info.show();
}
function sensor_enter(){sensor_state = false;}
function sensor_leave(){sensor_state = true;}
function add_sensor(element){
element
.on("mouseenter", sensor_enter)
.on("mouseleave", sensor_leave);
}
//Setup jqgrid
$("#list").jqGrid({
datatype: "local",
width: 600,
colNames:['EID', 'Title','First name', 'Last name', 'Contact', "Dropdown"],
colModel:[
{name:'id',index:'id', width:20, sorttype:"int"},
{name:'title',index:'title', width:90},
{name:'name',index:'name', width:50, align:"left"},
{name:'lname',index:'lname', width:50, align:"left"},
{name:'contact',index:'contact', width:25, align:"center", classes:'contact'},
{name:'dropdown', index:'dropdown', hidden:true, classes:'dropdown'}
],
rowNum:10,
rowList:[5,10,15],
pager: '#pager',
viewrecords: true,
caption:"Employees",
onSelectRow: function(rowid, status, e){
var row = $("#"+rowid)
//"Hide" selection so that cell selection looks "cooler" :)
row.attr("class", "ui-widget-content jqgrow ui-row-ltr ui-state-hover");
},
onCellSelect: function(rowid, iCol, cellcontent, e){
if(iCol == 4){
if(last_row == rowid){
if(contact_info.is(":hidden")){
show_contact_info(rowid);
}else{
contact_info.hide();
}
}else{
show_contact_info(rowid);
}
last_row = rowid;
}
},
idPrefix: "emp_",
gridComplete: function(){
//Because the content is dynamic, we need to add it after the grid has finished
//This should be done for server generated content, ie the loadComplete event for server requests
add_sensor($("tr td.contact"));
}
});
$("#list").jqGrid('navGrid','#pager',{edit:false,add:false,del:false});
for(var i=0;i<=data_from_server.length;i++){
$("#list").jqGrid('addRowData',i+1,data_from_server[i]);
}
//Sensor for the dropdown container
add_sensor($("#contact_info"));
//Hide contact info on document click
$(document).click(function(){
if(sensor_state){
contact_info.hide();
}
});
Here is what it should look like
Here are all the references
Why must the ID attribute be unique on each page?
Using Classname (class) and ID in HTML
Writing efficient CSS
The difference between "return false;" and "e.preventDefault();"
return false vs e.stopPropagation();
.click
.children
.not
.on()
.offset()
.outerWidth()
.outerHeight()
jqGrid
jqGrid events
You just need to get rid of the additional hide() as you are hiding then toggling, overriding your toggle.
See this for instance with it working
http://jsfiddle.net/RxJer/11/
var nav = $('#nav');
nav.find('ul#nav').toggle();
var emp = $(this);
$("html").click(function() {});
$(document).bind('click', function(e) {
var target = $(e.target); //2
var dropdown = target.parents('#nav').find('li.menu ul.dropdown');
dropdown.toggle();
});
Try this:
$(document).bind('click', function(e) {
var target = $(e.target); //2
if (target.parent().is('#nav') || target.parent().is('.menu')) {
var li = target.closest('li.menu');
var dd = li.find('ul.dropdown');
var isVis = dd.is(':visible');
$("ul.dropdown").hide();
(isVis) ? dd.hide() : dd.show();
} else {
$("ul.dropdown").hide();
}
});
Related
The content loaded by ajax does not take the styles of the page
With ajax I am bringing content to upload my website with information. What the page does is load everything normally first, then execute the corresponding ajax, but when loading the ajax and placing the appropriate information, this information does not apply the styles of the web page. Here is an example of how my code would be: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <!-- Styles that you do not recognize --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <div id="content" class="div-short"></div> <script src="js/jquery.js"></script> <script> $.ajax({ type: 'POST', url: "http://localhost:8000/api/pag/5", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ // Dynamic information $('#id').html(data); } }); </script> </body> </html> If someone has some kind of solution or how it can be done, it is very useful for me. Thank you
Example Snippet In the example below... assume that const data is being returned from your ajax call ignore everything except the jQuery, since it's all just to show that styles come through-- the point is to focus on how the HTML is generated I'm aware I didn't use your exact code and IDs to create this snippet. That doesn't matter-- what matters is the educational takeaway you can get from seeing the data flowing. const data = '[{"species": "dog", "breed": "Husky", "name": "Kenna"},{"species": "cat", "breed": "Siamese", "name": "Jeff"},{"species": "dog", "breed": "Doberman", "name": "Bella"}]'; let parsed_data = jQuery.parseJSON(data); var html = ""; $.each(parsed_data, function(key, value) { html += '<div class="card"><h3>' + value.name + '</h3><p>Species: ' + value.species + '</p><p>Breed: ' + value.breed + '</p></div>'; }); $("#container").html(html); .card { margin: 20px; padding: 20px; background-color: #EEE; font-family: "Arial", sans-serif; cursor: default; } .card > h3 { color: blue; cursor: pointer; } .card > h3:hover { text-decoration: underline; } .card > p { color: #555; <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"></div> Explanation Notice how the first thing I did with the data was run jQuery.parseJSON() on it. This takes the result from a string representation to a javascript object. I then loop through the javascript object with $.each. I access the variables with the funcParam.keyName format (e.g. the first access value.name). I finally included the generated HTML in a variable, and then used .html() to add it to my container after the $.each (which is faster than using .append() on each iteration of the loop). See below where the HTML generation code would be placed: $.ajax({ type: 'POST', url: "http://localhost:8000/api/pag/5", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ // run your HTML generation code (like my Snippet example) HERE } });
If you deal with changes in DOM (via AJAX), you need to understand, that addClass() or something like toggleClass() will work only for currently present objects. All newly appended or loaded items will not be styled, unless they are chіldren of parents which have CSS for children. Loading external CSS sometimes is a hassle. Good practice in my case came to use variables in CSS. Examples of usage: you need to change skin of website/webapp, make a nightmode/daymode or just to style loaded elements correctly. As example, let's take initial color of text and background in variables: /* CSS for day mode */ :root { --textcolor: #333; --bgcolor: #fff; } JS allows you to change the variables in CSS (along with saving that information), here is handy JS snippet from Ciaran O'Kelly for manipulating with CSS variables: /** * Gets and sets css vars * get a css var: * cv('bgcolor') // Returns #ccc * set a css var: * cv('bgcolor','#f00') // Sets and returns #f00 */ function cv(n,v) { if(n[0]!='-') n = '--'+n //allow passing with or without -- if(v) document.documentElement.style.setProperty(n,v) return getComputedStyle(document.documentElement).getPropertyValue(n); } And finally, user function to change UI. Styles will be aplicable to all present and yet not loaded elements in DOM: function change_skin() { if($("#sk").text() == 'Night') { // Night mode skin cv('bgcolor','#666') cv('textcolor','#eee') // Change label $("#sk").text('Day') } else { // Day mode cv('bgcolor','#fff') cv('textcolor','#333') // Change label $("#sk").text('Night') } }
i think you need to format your data in html... example $('#id').append("<span class='yourclass'>"+ data.name +"</span>"); that way you make thediv with all the data and styles you need and then append it to your div #id
after get response add simple html with class for example $('#id').append('<p class="test">test</p>'); and in the head add the following line <style> .test { font-size: 50px; } </style> if your "p" get the given style that's means your problem with "data" variable
Is there a way I can edit a CSS variable via the CSS Class Title?
So I have someone who wanted a special class title to use so they could be able to change the padding of a div. I quickly created a class called .columnpadding so they could do this. Later I was asked to make a few more classes so they could change the padding across multiple pages. Instead of having to duplicate the css class over and over and change the padding for each, is there a way I could have the variable changed via the class title. For example. If the class title is .columnpadding-100 Is there a way to have a class with its padding at 100px? My website runs on Php and Less. Let me know if the coding would be too complicated. Im hoping its not something too crazy! Thanks!
So let's presume we have the following basic structure: div { border: 1px solid black; height: 10px; width: 10px; } <div class="columnpadding-50"></div> <div class="columnpadding-30"></div> <div class="dontchangeme"></div> <div class="columnpadding-10"></div> Using only vanilla JS we can easily achieve the desired result: var divs = document.querySelectorAll("div[class^='columnpadding-']"); for (let i = 0; i < divs.length; i++){ let psize = divs[i].getAttribute('class'); psize = psize.substring(psize.indexOf('-') +1, psize.length); divs[i].style.padding = psize + 'px'; } div { border: 1px solid black; height: 10px; width: 10px; } <div class="columnpadding-50"></div> <div class="columnpadding-30"></div> <div class="dontchangeme"></div> <div class="columnpadding-10"></div> Where we first select all divs containg class with value columnpadding- into a NodeList Then we retrieve a string of the each class attribute, and substring it from the - to receive the size Last but not least, we apply style.padding to our selected elements in NodeList And voilà, produces the expected result!
Use JQuery CSS - not needed, but here for the example div { display: inline-block; } HTML <div class="columnpadding-100">This has 100 padding </div> <div class="columnpadding-50">This had 50 padding </div> javascript / jQuery $(document).ready(function(){ // wait until the page is completely loaded $("[class^='columnpadding-']").each(function(){ // get every element that has a class starting with "columnpadding-" let classNamesString = $(this).attr('class'); // get the string of class nameS from this element let classNames = classNamesString.split(" "); // create an array of class names $.each(classNames, function(index, className){ // loop through the class names looking for the one we want if (className.startsWith("columnpadding-")) { // hey, this is the one we want let amount = className.substring(14); // get the amount after the hyphen $("." + className).css("padding", amount + "px"); // set the css for the padding on the element } }); }); });
JQuery Hidden / Visible Error
I'm newbie at Jquery. I want to make floating menu at my web site. I created div which is id="item" Below code is in my .php file also I want to activate item after pressing my button which is id='sidebarOpenfile'. <div id="item" style="float:left"> <?php include("leftmenu.php"); ?> </div> and my 'sidebarOpenFile' code is here <button id="sidebarOpenfile" class="toolbarButton" title="Toggle OpenFile" tabindex="5" data-l10n-id="toggle_sidebar_openfile"> <span data-l10n-id="toggle_openfile_label">Toggle OpenFile</span> </button> Also My .php file has viewer.js file and .css file. I wrote my .js file this code document.getElementById('sidebarOpenfile').addEventListener('click',function() { alert("Its working"); // For sure whether event is working or not working, This code works and gets alert $("#item").css('visibility','visible'); }); Also I wrote my .css file this codes #item { position:absolute; top: 10px; width: 200px; bottom: 0px; background:orange; left:0px; visibility:hidden; } Normally, After pressing button It changes item's css visibility from hidden to visible. But It seems not working and does not effect. For any helping I'll be appreciated.
For toggling visibility on click it's as easy as it can get. You don't need any pure javascript, just a (very) little jQuery: <script> $('#sidebarOpenFile').click(function() { $('#item').toggle(); }); </script> The toggle() function toggles the display state of the queried #item. To just hide or just show you can use: $('#sidebarOpenFile').click(function() { $('#item').show(); // or $('this').hide() } For the sakes of convention, it should be wrapped in a self-invoking anonymous function like: (function(){ $('#sidebarOpenFile').click(function() { $('#item').toggle(); }); })();
OK... I'll bite... first problem is the: document.getElementById('sidebarOpenfile').addEventListener() It is far easier in JQuery to just reference this with $('#sidebarOpenfile'), for starters... but the real problem that I am having is that I can't find 'sidebarOpenfile' anywhere in the rest of your code; the id of the div you appear to be trying to effect is 'item', not 'sidebarOpenfile'. This might very well be your issue. The other possibility is that you actually have the proper id in the php code, which you didn't display. UPDATE Ok... my bad, not enough sleep.. you were tight, the id is there, and in the correct place. $('#sidebarOpenfile').click(function(){$("#item").css('visibility','visible')}); This should work... but will only display the element. If you wish it to toggle, you have to add a little extra: $('#sidebarOpenfile').click(function() { if ($('#item').css('visibility')=='hidden') { $('#item').css('visibility', 'visible'); } else { $('#item').css('visibility', 'hidden'); } });
Could you use something like: $('#item').fadeToggle("fast", "linear"); //this will toggle the visibility back and forth and do it gradually or $('#item').removeAttr('visibility'); //this will simply remove the visibility attribute thus making it visible by default
Try this: $('#item').on('click', function(e){ $(this).css('display','none'); });
You can toggle element's visibility property with this simple jQuery script: $(document).ready(function () { var item = $('#item'); $('#sidebarOpenfile').click(function() { if (item.css('visibility') == 'visible') { item.css('visibility', 'hidden'); } else { item.css('visibility', 'visible'); } }); }); jQuery fiddle vs javascript fiddle
ID or Class for textarea?
I was working on a tooltip from scratch. The code for the tooltip has been added below. Issue with following code: The tooltip fades in and out on focussing or blurring on the text-area but the problem is, all the tooltips (tooltips corresponding to all the elements) fade in and out simultaneously. The second issue is that the value of the text-area is same in all the tooltips which is the value of the first text-area. PHP <?php for($j; $j<5; $j++) { ?> <tr> <td style="position:relative"><?php echo CHtml::activeTextArea($PackageDeal,"package[$j][1]") ; ?> <div style="color:#0D776e;font-size:15px;font-family:calibri;padding:1%;margin:0 0.5%;;word-wrap:break-word;display:none;z-index:100;width:200px;mion-height:25px;position:absolute;top:30px;"></div> </td> </tr> <?php }?> Jquery <script src="jquery-1.8.3.min.js"></script> <script>$(document).ready(function(){ $("textarea").focus(function(){ $("td div").fadeIn(400).css({"background-color":"#E7F1F0","border":"1px solid #86BBB6"}); $("td div").html($("textarea").val()); }); $("textarea").blur(function(){ $("td div").fadeOut(400).css({"background-color":"#E7F1F0","border":"1px solid #86BBB6"}); }); $("textarea").keyup(function(){ $("td div").html($("textarea").val()); }); }); </script> The issue is that I'm using this tooltip in a PHP for loop and I tried variety of ways so that the tooltip is functional. I need to ask whether I should keep an Id / Class for the tooltip (div element) and for the text-areas so that the text shown is different in all and all of them don't show up simultaneously. Also I would like to know whether this is a jquery, php or html related issue. Thanks in Advance! P.S. the tooltip works fine for single element.
Because your page would have a lot of <td><div></div></td>s from generated HTML (by PHP), and all matches td div, all of them would show if you were to call $('td div').//so on So you need to specify which one you want to show, and in your case you want the one near to the element that is focused or blurred. jQuery is good at that. $("textarea").focus(function(){ var targetArea = $(this); targetArea.siblings('div').fadeIn(400).css({"background-color":"#E7F1F0","border":"1px solid #86BBB6"}) .html(targetArea.val()); }); Also, as per #joeltine answer, you also need to show only the html for that textarea too, so also use the same $(this) in your html call parameter. For performance, you may want to chain them together and cache $(this) to a variable as above too - the $ constructor is expensive. And one more thing, you seem to set css when it fades in and fades out, but they are not necessary - when you can set it in a css file instead. Their style can't be seen if you set it beforehand and they are not shown (by display: none) anyway. $("textarea").focus(function(){ var targetArea = $(this); targetArea.siblings('div').fadeIn(400).html(targetArea.val()); }); and in CSS: /* You really want to apply this css to all "td div" for this one! */ td div { background-color: #E7F1F0; border: 1px solid #86BBB6; /* More styles for tooltips, such as display: none; position: relative; etc... */ }
#luiges90 addressed your one issue... and I'll also mention the reason your tooltips are all showing the same value (the value in the first text area on the page) is because your selector $('textarea') is selecting ALL the textareas on the page. When you call .val() on that, by default, it only returns the value of the first element in the collection. So in short, in your focus event just use something like this: $("textarea").focus(function(){ var $this = $(this); $this.siblings('div').fadeIn(400).css({"background-color":"#E7F1F0","border":"1px solid #86BBB6"}) .html($this.val()); });
Use a class for your textarea, i.e. myTxtArea and use $(this) like $("textarea.myTxtArea").focus(function(){ var el=$(this); el.closest("td").find("div").fadeIn(400).css({"background-color":"#E7F1F0","border":"1px solid #86BBB6"}); el.closest("td").find("div").html(el.val()); }); An Example Here.
This is what I was talking about: HTML <table> <tbody> <tr> <td> <textarea class="editable">This is a texarea.</textarea> <div class="uneditable"></div> </td> </tr> ... More rows ... <tr> <td> <textarea class="editable">This is a texarea.</textarea> <div class="uneditable"></div> </td> </tr> </tbody> </table> jQuery Note the use of textarea.editable, text.uneditable, $(this).siblings('.uneditable'), and $(this).next('div.uneditable'). The div.uneditable is a little gratuitous here, but I offer it as a demonstration of overselecting (in case there were also a span.uneditable or whatever next in flow with the div.uneditable...). $(document).ready(function () { var $editable = $('textarea.editable'); $editable .focus(focus) .blur(blur) .keyup(keyup); function focus() { $(this).siblings(".uneditable").fadeIn(400).css({ "background-color": "#E7F1F0", "border": "1px solid #86BBB6" }) .html($(this).val()); } function blur() { $(this).siblings('.uneditable').fadeOut(400).css({ "background-color": "#E7F1F0", "border": "1px solid #86BBB6" }); } function keyup() { $(this).next("div.uneditable").html($(this).val()); } }); http://jsfiddle.net/fuFuT/
The reason why all of them go at the same time, is because you select all of them, $("textarea") returns all matching elements. To prevent that behaviour, create this (I didn't include the event functions for readability) // Do things for each matching elements, separately $("textarea").each(function() { $(this).focus(); $(this).blur(); $(this).keyup(); }); As for the id / class for the tooltip: it is generally better to keep the CSS external, so in that case, giving the tooltips a CSS class would be better.
PHP: Navigating through data
I have a PHP site I'm working on, and need to allow the user to select data and have different data appear on the next DIV (see attached image). Essentially I'd like a DIV (overflow:auto, so it scrolls) to populate using the SQL SELECT statement, and allow a user to click on a list item. That item creates a new SELECT statement for the div to the right, if that makes sense. Any input on the best way to go about this? New to PHP, not HTML/CSS though. Zach
I think the best way to achieve this is with jQuery (a JavaScript-Library). I is quite easy to use, and if you got the trick, you can do amazing things with it. For PHP/MySQL, you could use jQuerys Ajax functionalities (see http://api.jquery.com/jQuery.ajax/). Use the callback to display the loaded data (see below). Here is a very simple example on how to show another div (in which could be more links to select) with dynamic content. If you combine this with Ajax, you should get what you need. Include jQuery in within head tag: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> Code for the body: <!-- First Box: click on link shows up second box --> <div id="selectOne" style="float: left; margin-right: 10px; border: #666 thin solid; padding: 10px;"> One<br /> Two<br /> Three </div> <!-- Second Box: initially hidden with CSS "display: none;" --> <div id="selectTwo" style="float: left; margin-right: 10px; display: none; border: #666 thin solid; padding: 10px;"></div> <!-- The JavaScript (jQuery) --> <script type="text/javascript"> //Do something when the DOM is ready: $(document).ready(function() { //When a link in div with id "selectOne" is clicked, do something: $('#selectOne a').click(function() { //Fade in second box: $('#selectTwo').fadeIn(500); //Get id from clicked link: var id = $(this).attr('id'); //Depending on the id of the link, do something: if (id == 'one') { //Insert html into the second box which was faded in before: $('#selectTwo').html('One<br />is<br />selected') } else if (id == 'two') { $('#selectTwo').html('Two<br />is<br />selected') } else if (id == 'three') { $('#selectTwo').html('Three<br />is<br />selected') } }); }); </script> So if you would use jQuerys Ajax-Functionality, you could use something like that (not tested!): $('#selectOne a').click(function() { var id = $(this).attr('id'); $.ajax({ type: 'POST', url: 'getYourData.php', data: 'thisIsSentToPHPFile='+id, success: function(msg){ //everything echoed in your PHP-File will be in the 'msg' variable: $('#selectTwo').html(msg) $('#selectTwo').fadeIn(500); } }); }); The getYourData.php could be: $id = $_POST['id']; $query = mysql_query('SELECT * FROM table WHERE id='.$id); $result = mysql_fetch_assoc($query); //Now echo the results - they will be in the callback variable: echo $result['tablefield1'].', '.$result['tablefield2']; Give it some tries, tweak it a little bit and you should get it working.
The most straightforward way to do this is probably to make the right portion an iframe. Then each item in the middle list could be a link like so: Company 2 In displaySubItems.php you would then use the $_GET['company'] value in your select statement to populate the table. Alternatively you could make use of AJAX methods to populate the table on the right though I'm personally not that familiar with AJAX so I can't tell you more about that. Also I suspect iframes are more widely supported. EDIT: changed some parts based on one of your comments