March 31, 2011

resizing div width with browser resize

Question by leora

i recently asked this question on how to have a container div width set so i could avoid scrolling for folks with wide monitors. I got a great answer basically to combine min-width with display: block;

I now have one follow up. The accepted answer works great if the browser up front is set to be wide but if at first its not wide and a user stretchs the window, the div container doesn’t change or stretch.

is there anyway i can take this one step further and reset the width of the div when the browser window itself resizes.

Answer by clairesuzy

you could use absolute positioning,

#panel {
 position: absolute;
 top: 50px;
 left: 50px;
 right: 50px;
 bottom: 50px;
 background: #eee;
 border: 3px double #000;
 overflow: auto;

<div id="panel"><p>I shrink and grow</p></div>

overflow:auto; sets a scroll bar on the #panel itself if the content requires it.. which may not be desired?

Working Example

Answer by Starx

How about estimating the area of screen, your page should cover and writing the width in percentage?

For example,

#wrapper { width: 90%; }
March 30, 2011

What is wrong with this MySQL syntax?

Question by tekknolagi

INSERT INTO homework_MarcWed30-2011 ('Teacher', 'Class', 'Period', 'Assn') 
                              VALUES ('a', 'a', 'a', 'a')

i get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-2011 (Teacher varchar(30), Class varchar(30), Period varchar(30), Assn varchar(‘ at line 1

what is going on?

on a side note, the create table statement does not work for me:

mysql_query("CREATE TABLE homework_MarcWed30-2011 (Teacher varchar(30), Class varchar(30), Period varchar(30), Assn varchar(400))","mysql_connect('#####', '#####', '#####')") OR die(mysql_error());

Answer by Positive

Column names should be out of quotes they can be surrounded by back quote “ but not with single or double quote.

 INSERT INTO `homework_MarcWed30-2011` (`Teacher`, `Class`, `Period`, `Assn`)
 VALUES ('a', 'a', 'a', 'a')

if there is – in table name you can still use by surrounding name in back quotes “.

Answer by Starx

Try this query

INSERT INTO `homework_marcwed30-2011` (`Teacher` ,`Class` ,`Period` ,`Assn`) VALUES ('a', 'a', 'a', 'a');

Variation, without field quotes

INSERT INTO `homework_marcwed30-2011` (Teacher ,Class ,Period ,Assn)
VALUES ('a', 'a', 'a', 'a')

Variation, without field defination

INSERT INTO `homework_marcwed30-2011` VALUES ('a', 'a', 'a', 'a')

For the table creation part

mysql_query("CREATE TABLE `homework_MarcWed30-2011` (Teacher varchar(30) NOT NULL, Class varchar(30) NOT NULL, Period varchar(30) NOT NULL, Assn varchar(400) NOT NULL);","mysql_connect('#####', '#####', '#####')") OR die(mysql_error());

Your error is that you didn’t define whether to allow Null or not.

add an anchor and onClick to a link

Question by Denoteone

I have an image with a link that when clicked I would like the user to be brought to an anchor on the same page and then the cursor to be focused on the input directly below.

<a onclick=";" href="#newssection"><img src="images/newsletter_slide.jpg" /></a>

When it is just the onClick it works but does not scroll the page down and when I use the anchor it goes to that section but does not focus.

I switched around the onClick and the href and it didnt help

Answer by Kyle

Try this.

<a onclick=";return false;" href="#">click me</a>
<form name="newsletter" id="newssection">
  <input id="email" name="email"/>

Answer by Starx

I think a simple

document.getElementById('yourEmailField').focus(); should do the trick.

It will automatically focus to the element, and if needed scroll too.

March 29, 2011

How to detect the path to the application root?

Question by auge

I’m trying to dynamically detect the root directory of my page in order to direct to a specific script.


It prints /myName/folder/index.php

I’d like to use in a html-file to enter a certain script like this:

<a href="<?php $_SERVER['DOCUMENT_ROOT'].'lib/logout.php'?>">log out</a>

This seems to be in bad syntax, the path is not successfully resolved.

What’s the proper approach to detect the path to logout.php?

The same question in different words:

How can I reliably achieve the path to the root directory (which contains my index.php) from ANY subdirectory? No matter if the html file is in /lib/subfolder or in /anotherDirectory, I want it to have a link directing to /lib/logout.php

On my machine it’s supposed to be http://localhost/myName/folder (which contains index.php and all subdirectories), on someone else’s it might be http://localhost/project

How can I detect the path to application root?

Answer by Starx

Try this,

<a href="/lib/logout.php'?>">log out</a>

This jumps to the root directly.

Method for over-riding various jQuery events if a global var is not set

Question by Dunhamzzz

I have various jQuery click and submit events on my site, but some of them I only want to activate if the user is logged in (yes I have all required server-side validation), if they are not logged in, I want a jQuery UI dialogue to pop up.

If the user is logged in the page will have a javascript variable set: with var uk = 'randomkey';

What is the best method for this? Off the top of my head some sort of global function which checks for user value and fires the dialogue and returns false? Or is there a neater/optimised way of doing it.

Answer by Richard Neil Ilagan

Since you say that you’re already performing server-side validation, I’d suggest that you take away all the JS behavior you want for logged-in users, and those for not-logged-in users to two separate JS files, and load the relevant one into the page before your server even flushes the HTML back to the browser.

Answer by Starx

It would be better if you would filter the elements while the page is loading, to avoid unauthorised access. Try to avoid complexity as much as possible.

But if you really need to do this, you can send a ajax request to detect if user is logged in (Relying on the client’s browser by setting class name is a bad idea, it can be easily tampered).

Just an example

    { action: 'checklogged' },
    function(data) {
        //if the response come as `no` and `yes`
        if(data=='no') {
            //dialogbox code
        else {
           var uk = 'randomkey';

Dynamically generate a <li>?

Question by jimmy_in

<span id="n-email" class="email-btn"><a href="#."></a></span>

On clicking this, a list item with a text field shows

<li id="new" class="select">
        <input type="text" id="emails" class="add-email" value="Untitled" onfocus="if(this.value=='Untitled'){this.value=''}" onblur="if(this.value=='')  {this.value='Untitled'}"/>

Suppose I filled something in this input field and press enter.
On pressing enter I want to fire a event which would

  1. Remove the <li> containing the input field.
  2. Insert new <li> in its place, like

        <a href="#.">
            //here comes the value what we entered in the input field of above li//

Answer by Starx

First, you need to hide the #new row, then you need to use keypress event to catch the enter key, finally use the append() method to insert a new element.

Here is a example based on your script

$(".email-btn").click(function() {

    value = $(this).val();
    code= (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {



jQuery script BEFORE HTML elements

Question by Hello_jQuery

Is it possible for jQuery to bind events to elements if the jQuery script block comes before the html tags in the page?

As an example, this does not work:

    $('a').bind('click', function() {

<a href="#Hello">Greetings</a>

Yes, I could just put the script after the elements, but hey, maybe I don’t wanna. Just curious if this is the only way.

Answer by Felix Kling

Yes, if you put the code in a ready[docs] event handler (and fix your syntax errors ;)):

$(function() {
    $('a').bind('click', function() {
        // jQuery way would be: $(this).html()

Answer by Starx

Another way is to execute the script during $(window).load() event

$(window).load(function() {
    $('a').bind('click', function() {

Now the bind will occur once all the document is fully loaded.

March 28, 2011

Looping through Dynamic JSON String

Question by Starx

I have a POST request which receives a JSON String as a result. The fields, the values, or how deep the array is? These all are unknown. So, I need to loop through each of the json value, its index and its value and perform actions based on it.

    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function() {
       key = data.key; //i need to retrieve the key
       value = data.value; //i need to retrieve the value also

       //now below here, I want to perform action, based on the values i got as key and values

How can i get the values of JSON seperated as key and value?

Answer by Starx

Sorry, guys, but I solved it myself. Please dont be angry with me. (I will delete the question if it is required by the community.)

    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function(key,value) {
       //now below here, I want to perform action, based on the values i got as key and values

How to Add text with superscript to a Button

Question by Sajja

I have a HTML button like

<input type="button" id="button" onclick="showSuper()" value="Click Me!" />

Inside JavaScript, I have

var showSuper = function() {
    var btn = document.getElementById('button');
    var spanSuper = "<sup>3</sup>";
    btn.value="You Clicked Me " +  spanSuper;
    //btn.value = "You Clicked Me " + <sup>a</sup>;

With the above function the button value is getting replaced with You Clicked Me <sup>3</sup>

I also tried with the comment statement that also didn’t succeed. How can add a superscripted text to the button?

Answer by Starx

You do not need script to do this. Use this instead

<button name="button" id="button" onclick="showSuper()">Click Me!</button>


var showSuper = function() {
    var btn = document.getElementById('button');
    var spanSuper = "<sup>3</sup>";
    btn.innerHTML= "You Clicked Me " +  spanSuper;

Check Demo. Updated Demo with your solution

reading index value of a table row with many cells and reading the value from it using Jquery

Question by user679460

//PHP array   
 $Cashups = array(
        'cashup_id' => 146456,
        'display_time' => 'Wed 16th Mar, 9:55pm',
        'terminal_name' => 'Bar 1',
        'calculated_cash' => 389.20,
        'actual_cash' => 374.6,
        'calculated_tenders_total' => 1,551.01,
        'actual_tenders_total' => 1,551.01
        'cashup_id' => 146457,
        'display_time' => 'Wed 16th Mar, 9:56pm',
        'terminal_name' => 'Bar 2',
        'calculated_cash' => 493.3,
        'actual_cash' => 493.3,
        'calculated_other' => 1509.84,
        'actual_other' => 1509.84


<?php foreach ($Cashups as $Cashup) { ?> 
    <td class="Left"><?php echo $Cashup['display_time']; ?></td>
    <td><?php echo $Cashup['terminal_name']; ?></td>
    <td><?php echo number_format($Cashup['calculated_cash'], 2); ?></td>
    <td class="clickchange"><a  href="#"><?php echo number_format($Cashup['actual_cash'], 2); ?></a></td>
    <td><?php echo number_format($Cashup['calculated_other'], 2); ?></td>
    <td><?php echo number_format($Cashup['actual_other'], 2); ?></td>
<?php } ?>


I am able to input text boxes when clicked on the link(clickchange) with the help of an answer sent by user on stackoverflow.
I can read the values but am not able to read the indexes of the links when clicked. I would like to know how to apply each on function to read the indexes of the link. Once I read the inexes I can then update the td with thier respective values.

Please help. How do I read text?

Answer by Starx

I am guessing you want the index when clickChange is clicked.

$("td.clickchange").click(function() {
    var i = $(this).parent("tr").index();

Please fill the form - I will response as fast as I can!