August 31, 2012

jquery selector contains equals sign

Question by John Buckwell

I am using a jQuery selector to check for characters in href:

var param = "something";
$("a[href*="+param+"]").css("color", "red");

This works fine until “something” contains an = sign. Eg:

var param = "xkey=123";
$("a[href*="+param+"]").css("color", "red");

then I get no result. Anyone know a solution?

Answer by Starx

It is behaving that way becuase, at the end it will translate to ambiguous selector i.e. $("a[href*=xkey=123]") which indeed is invalid.

Escape the equal sign with \ infront and wrap the parameter part with a quote

var param = "xkey\=123";
$("a[href*='"+param+"']").css("color", "red");

jquery slide out from record

Question by Matthew

I am looking for some advice on an idea which i am unsure if i can do it or not…

i am loading records out of a database and listing them in individual divs and adding an id number from the databse to the divs,the divs are about 100px wide and right across the screen..

i am wondering if i can use some kinda of plugin by jquery so that if i click on the record a tab would slide out from the right hand side with more data on that individual record from the database.. and then i could close it and it would side back so i can only see the records again..

i have had a bit of a look at the jquery ui page with all the demos but i didnt really find anything…

any help or pointers would be great.. even if u know of something simllar ill be happy to look into it…

thanks in advance for any help

Answer by ComputerArts

Ok so here’s my fiddle

HTML (standard containers, etc)

<div id="container">
    <div id="buttons-container"></div>
    <div id="record">
        <div id="record-content"></div>            
        <a href="#" id="bt-close" onclick="closeRecord(); return false;">Close</a></div>

    margin:0 10px 10px 0;

a { color:#fff; }

#container {

#record {


//your data in a array of objects (could be something else)
var data = {
    1 : {name:'Record 1', text:'This is the text 1', options:'Anything 1'},
    2 : {name:'Record 2', text:'This is the text 2', options:'Anything 2'},
    3 : {name:'Record 3', text:'This is the text 3', options:'Anything 3'},
    4 : {name:'Record 4', text:'This is the text 4', options:'Anything 4'},
    5 : {name:'Record 5', text:'This is the text 5', options:'Anything 5'},
    6 : {name:'Record 6', text:'This is the text 6', options:'Anything 6'},
    7 : {name:'Record 7', text:'This is the text 7', options:'Anything 7'},
    8 : {name:'Record 8', text:'This is the text 8', options:'Anything 8'},
    9 : {name:'Record 9', text:'This is the text 9', options:'Anything 9'}

$(document).ready(function() {

//dynamically populate the entries
function populateEntries() {
    for (entry in data){
        $('#buttons-container').append('<a class="bt-record" href="#" onclick="showRecord(' + entry + '); return false;">' + data[entry].name + '</a>');

//show the record
function showRecord(id) {
    //create the html
    var html = '';
    html += '<p>Name : ' + data[id].name + '</p>';
    html += '<p>Text : ' + data[id].text + '</p>';
    html += '<p>Name : ' + data[id].options + '</p>';
    $('#record').animate({right:0}, 500);

function closeRecord() {
    $('#record').animate({right:-240}, 500);

In this example, I populate the records dynamically, but if you want a SEO friendly way of doing it, you can create the HTML in the page directly. Let me know if you have questions.

Answer by Starx

Sure, let me show you a simple example. It is rather very easy

    <tr class="recordrow" id="row-1"> <!-- row-X will be the unique way to identify the row -->
       <td>...</td> <!-- The record field -->

<!-- Now we create the details Div, but as reference to the `row-X` -->
<div class="details" id="details-1">
   ... More details of the records

then a simple jQuery snippet like this will get the job done:

$(".recordrow").click(function() {
    var divid = "details-" + $(this).attr('id').split("-")[1]; //Create the id of the div
    $("#"+divid).show().animate({ "left": '200px'}); //Bring the div from right to left with 200px padding from the screen


How to store session while sendRedirect

Question by Thunderbird

I have a condition where I want to remove the attribute from the session and I am doing response.sendRedirect after that.

But I am not sure if it will remove the session attribute ? Any thoughts ?

P.S. I have to do sendRedirect, I cannot use forward.


ANSWER : Just a little debugging solved my concern. I checked the session attribute value by getting the variable and it was null. So it removed the variable from the session.

Answer by Starx

Yes, if Constants.USER_REQUEST_URI gives the correct name as it is stored in session, then it will remove them.

Session work differently than GET and POST request so redirecting and forwarding will make no difference.

Good way to confirm this, would be to check if the variable is accessible after the redirect

August 29, 2012

Disabling form button onClick, and then submitting the form

Question by bevanb

My form lets users submit a poem.

Sometimes, there’s a field for a new user name on that page (if nobody’s logged in). In that case, I want to override the button click so that it signs them up first:

$('#submit-poem').click ->
  $('input[type=submit]').attr('disabled', true)
  if $('#new_poet_name_field').length
    signUp();  // This will submit the poem form after registering
    console.log("A poet was already logged in!")

This used to work fine. But now, when there is no new_poet_name_field, the submit button stays disabled. Returning true used to submit the form. Now, I have to explicitly do $('#new_question')[0].submit() if there is no poet_name_field.

Why doesn’t the form submit when true is returned? My workaround is worrisome; it seems possible that the form might submit twice now: once when I explicitly submit it, and once when true is returned.

Answer by brains911

You should bind to the form ‘submit’ event and use preventDefault/return false when you want someone to sign up instead of submitting the poem. This way there is no need to do any disabling/enabling of buttons.

Answer by Starx

I dislike the idea of not having a form. Its invalid and sure to not follow HTML’s Specification.

Every constructive form elements should be wrap inside a form tag. You can control the submission of form in more than one way.

The code you are using is horrible

  1. WHY?? Is there more than one submit button? The code below disables every submit button on the page, which can be of other forms too.

    $('#submit-poem').click ->
      $('input[type=submit]').attr('disabled', true) 
  2. This is wrong way to check the authenticity of submission, it can be easily manipulated with tools like firebug.

    if $('#new_poet_name_field').length

If finding out if the user is logged in or not that important, then you can quickly send an ajax request to a service page, that gets you that information

$('#submit-poem').click(function() {
    $(this).attr('disabled', true)
    $.post("yourservicepage.php", {}, function(data) {
          // RE suppose, data is the boolean value from server indicating logged in or not
          if(data != true) {
             signup(); //if not logged in then signup
August 28, 2012

Graphical editor using Javascript

Question by aakashbhowmick

I want to make an online card-making application. It should basically allow users to place available images into the template of the card, write text on it and decorate it – basic card customization. What javascript graphics library would be useful for this project ? Finally I would like to have a high resolution/vector image as the output which can be printed easily.

Answer by AlienWebguy

Raphael is great for SVG, etc.

Answer by Starx

To have a high resolution/vector image, you have to work with SVG (Scalable Vector Graphics), so far the web browser only support this. There are two ways you can do these.

  • Looking up for canvas libraries. I prefer Raphael as it supports SVG and animations as well.
  • With HTML5 and its Canvas features also you can create such system.
August 27, 2012

Giving text labels to integer ranges in PHP

Question by xxdrivenxx

I am attempting to take simple number ranges (in the example of this project, I am working with different increments of money for each user. FAKE money, by the way…) and group them into classes that can be displayed publicly instead of the absolute number.

Here is a rough sample of code for the long way to write this function as an example:


if($money > 0 AND $money < 5000) {
    $class = 'Poor';
} elseif ($money >= 5000 AND $money < 25000) {
    $class = 'Lower Class';
} elseif ($money >= 25000 AND $money < 100000) {
    $class = 'Middle Class';
} elseif ($money >= 100000) {
    $class = 'Upper Class';
echo $class;

Now, I know this function will work, but it seems like an absolutely awful way in going about writing it, since if more $class’ are added, it becomes far too long.

Now my question is: Is there a shorter way to write this? Possibly using range() and/or an array of values?

Answer by alfasin

I would go for something like this:

function getClass($sal){
    $classes = array(5000=>"poor", 25000=>"Lower Class", 100000=>"Middle Class");
    foreach ($classes as $key => $value) {
        if($sal < $key){
            return $value;
    return "Upper Class";

$salary = 90000;
$sal_class = getClass($salary);    
echo "salary class = $sal_classn";

sal = Middle Class

Answer by Starx

A bit similar to above answer, but a better one. I will suggest using OO approach.

Class Foo {
    protected $class = array(
        array("poor", 0, 5000),
        array("medium", 5000, 25000)

    function get_class($amount) {
       foreach ($this -> class as $key => $value) {
           if($amount > $value[1] && $amount < $value[2]) {
              return $value[0];
       return null;

    function add_class(array $arr) {
        $this -> class[] = $arr;


$obj = new Foo();
$obj -> get_class(6000); //Outputs: medium
$obj -> add_class(array("rich", 25000, 50000)); //Add a new class
$obj -> get_class(35000); //Outputs: rich
August 26, 2012

Singleton and class instantiation in php

Question by Bojan Savic

There is a class like this in codeigniter framework ( I edited it to be more clear, full function is here

function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
        static $_classes = array();

        // Does the class exist?  If so, we're done...
        if (isset($_classes[$class]))
            return $_classes[$class];


        $_classes[$class] = new $name();
        return $_classes[$class];


So, first time when class is loaded ( passed to this function), it will be saved to this static variable. Next time when the same class is loaded, this function checks if class exists already ( if it’s already assigned to static, cached, I’m not sure how in memory is this stored) and if it exists, it’s loaded ( NOT *instantiated* again )

As far as I can see, the only purpose is to save time or memory and not instantiate the same class twice.

My question here is: Does really instantiating a class can take up memory or consume loading time so it has to be cached like this?

Answer by ctrahey

CodeIgniter is is geared for rapid prototyping, and is really not a good example of enterprise patterns in almost any cases. This behavior is related to their design choice of the relationship the “controller” has to almost all other objects; namely that there is exactly one of almost anything (only one instance of controller, only one instance of each library, etc). This design choice is more for rapid development (justified by the developer “not having to keep track of as much” or some such…).

Basically, there is memory saved by not instantiating an object (as much memory as it takes to store the object’s instance variables) and if the object’s constructor tries to do a fair bit of work, you can save time, too.

However, the appropriateness of the single-instance imperative is clearly not universal; sometimes you really do want a new instance. When you can justify this, choose a better framework.

Answer by Starx

Its rather a simple concept, utilizing singleton-pattern it makes sure that one class is instantiated only once during an application’s execution cycle.

This sort of concept apply for libraries more. Lets see a basic example:

class Authenticate {
     public function login($username, $password) {

     public function logout() {


Now, through a execution of a page, there is hardly any case that the object of the above class, needs to be created more than once. The main thing to understand is Utilization of resources

And YES, instantiating same class over and over again will without a doubt add up in the memory, although it might be negligible like in the example I have shown, but it does affect.

August 23, 2012

I need to put script from jsFiddle to work

Question by Voyager

I have one small problem… I need to put this script to work on my page, but i don’t know how to do it…. What to copy where, and how to make jquerry working! I don’t have pre-knowledge about jquerry and don’t know how it functions…

I need instructions like where to paste which code (head, body), and what file to make (js, html) also what values to change so it works! Can someone zipp example or something?

I would be forever gratefull!


Answer by Starx

We can see the full paged version of a fiddle by adding an /show/ at the end.

Save this version of the fiddle. It contains all the scripts and resources needed for that particular fiddle to run.

Compare and meet them in your application.

August 22, 2012

Online chat with database – Fastest way?

Question by krtek

Hello I’m going to create a web based chatting program.
All chats are private, no groupboxes.

I need to keep a log of all the chats.
My idea is to push all messages to a mysql database and then check this database every half a second for incoming messages.

Is this the best way for creating the web app? The site should support 2000 users chatting simultaneously.

Are there maybe better options? I’ve seen people talking about multiple databases, text files, a combination of TCP/IP (IRC) and SQL, etc.

Answer by Starx

MySQL is capable of handling large amount concurrent request at a time, but how you manage and maintain the database is a main point.

Perfectly maintained and indexed table should show no problem. Keep the table’s structure as simple as possible. Something like

|    from        |     to       |   message      |

And, there is no perfect way to create a chat program. Depends on lots of other factors like

  • Request Type: AJAX or Comet or WebSocket
  • Application Coding: No garbage Coding, Clean OO codes following one of more Design pattens
  • Caching: Cache most of the static information as possible.
  • Data Archiving or Transaction Handling
  • Query What do you fetch together with the message (may be those things could be cached before. These things include names, avatar etc)
August 21, 2012

How to style <ul> and <li> without affecting MENU

Question by dotman14

How can I apply a different styles to the same elements at different parts of my HTML/CSS.
I have tried the following it doesn’t seem to work.


   <div class="menu">
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>

somewhere in the webpage

   <div class="others">
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>
         <li><a href="#"><Link 1</a></li>


     .menu ul,li{
         color: rgb(242,253,255);   
         list-style: none;
         text-decoration: none;
         font-size: 20px;
         font-family: chaparral pro;

.others ul,li{
         color: rgb(242,253,255);   
         list-style: none;
         text-decoration: none;
         font-size: 10px;
         font-family: chaparral pro;

Answer by Starx

You made a tiny mistake you generalized style of li in the following part.

.others ul,li { ..... }

The above will apply to ul inside .others and all the li through out the page. Just use

.others ul, .others li {

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