Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

Sorting 2D associative arrays in PHP

July 13th, 2009  |  Published in php

Surprisingly, it took me a long time to find this solution so I decided to post it for anyone who had a situation similar to mine.

Let’s say you have the following 2D associative array in PHP of fruits and their corresponding prices and you want to have them sorted by price:

$fruits = array
(
    [0] => array
        (
            ['product'] => 'banana',
            ['price']     => 2.99
        ),
    [1] => array
        (
            ['product'] => 'apple',
            ['price']     => 1.99
        ),
    [2] => array
        (
            ['product'] => 'durian',  //these smell by the way - i do not know how people can like them =)
            ['price']     => 19.99
        ),
    [3] => array
        (
            ['product'] => 'starfruit', //not too stinky but still stinky nonetheless
            ['price']     => 5.99
        )
);

Continue reading →

Dynamic or on-the-fly percentage calculations with JavaScript

July 12th, 2009  |  Published in javascript


Here is a simple JavaScript function that does dynamic or on-the-fly percentage calculations.

Demo




You have saved 50 %

Continue reading →

The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag

April 8th, 2009  |  Published in javascript  |  4 Comments

I recent ran into an interesting IE bug involving the following bit of html code:

<a href="javascript: void(0);" onclick="dosomething();">click me</a>

I honestly did not write this one but I will leave names out of this to protect the innocent =)

The void(0) JavaScript code is usually used to prevent loading or reloading of the page when the user clicks the link.

What we were trying to do here was have the dosomething JavaScript function execute when a user clicks on the link. This works fine in FireFox, Chrome, Safari but not IE. When a user clicks on the link in IE, nothing happens: i.e. (no pun intended) the JavaScript does not execute.

It took us a good amount of time to realize what the issue was with IE. It turns out that the void(0) function was preventing the onclick event to fire.

Although it may not be pretty, this is what we ended up doing and it appears to be cross-browser friendly:

<a href="<?=$_SERVER['PHP_SELF'];>#" onclick="dosomething();">click me</a>

Anyway, I hope this helps someone out there in the universe.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

How to randomly order or select rows in a MySQL query

October 28th, 2008  |  Published in mysql

I was looking for a way to order the rows randomly in a MySQL query and the solution was not easy for me to come by. I am posting the solution here in hopes of helping others.

1
2
3
SELECT * 
FROM my_table
ORDER BY RAND()

RAND() returns a random floating-point value but functions to randomly order the selection of rows in the above usage.

If you combine the query with LIMIT, you will end up with a random selection of rows from your table.

1
2
3
4
SELECT * 
FROM my_table
ORDER BY RAND()
LIMIT 3

Assuming you have more than 3 rows in your table, you will always get 3 random rows from the query.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

How to convert MySQL timestamp to PHP date type

October 5th, 2008  |  Published in mysql, php  |  5 Comments

Let’s say you have the following PHP code that extracts the date from the times table in your MySQL database. The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’

1
2
3
4
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
   echo $row['date'] . "<br />";
}

Continue reading →

How to count values with MySQL queries

October 5th, 2008  |  Published in mysql  |  13 Comments

Let’s say you have the following table called votes that keeps track of how people voted and you want a query to count the number of votes for you instead of having to loop through all the rows with a counter in PHP.

person vote
obama yes
mccain no
obama yes
obama no
mccain yes
obama yes
obama yes
obama no
mccain no

Continue reading →

How to confirm or prompt user for input via JavaScript

June 26th, 2008  |  Published in javascript


JavaScript has a built-in function called confirm which takes a string argument that poses the question to the user and gives them the option to click the OK or Cancel buttons and returns true if the user clicks OK.

Demo
green box

yellow box

Continue reading →

How to find and access parent nodes via JavaScript

June 26th, 2008  |  Published in javascript


Have you ever had to access a parent node from a given child node? In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the name attribute itsMe.

Demo
My name is notMe

My name is itsMe

My name is notMeEither

My name is tryAgain

My name is sorryNotMe

My name is nopeSorry

Continue reading →

How to loop through checkboxes or radio button groups via JavaScript

May 15th, 2008  |  Published in javascript  |  7 Comments


Do you have a form with checkboxes or radio buttons that you would like to loop through via JavaScript? This JavaScript function will do just that!

Demo
I like to program in:
PHP

Perl

Ruby

ASP


I like to eat:

Snickers

Hershey's

M&M's

Nerds


I like to drink:

Coke

Gatorade

Pepsi

Milk

Continue reading →

How to create your own customized calculator via JavaScript

April 26th, 2008  |  Published in javascript  |  8 Comments

This is a simple example of implementing a calculator with JavaScript and HTML. This calculator will only have the division, multiplication, addition, and subtraction operators but you can easily tack on more functions if needed.

Demo

Continue reading →

How to dynamically add content to a div and store the content to a cookie via JavaScript

April 14th, 2008  |  Published in javascript  |  9 Comments


This is an example of adding dynamic content via JavaScript by allowing the user type in the actual content.

Demo
Content to be added:

Your content will be added dynamically below:

Continue reading →

How to validate email format via JavaScript

April 1st, 2008  |  Published in javascript  |  11 Comments


This JavaScript demo verifies that an email address is in the correct format and that the user has typed in the same address in both fields to prevent mistyping of the address. I have borrowed the regex for verifying the correct email format from a different site.

Demo
Email:

Please type in your email again:

Continue reading →

How to dynamically remove/delete elements via JavaScript

March 26th, 2008  |  Published in javascript  |  25 Comments


This post is in response to one of the comments on have received regarding the removal of elements via JavaScript. I have taken the original function posted and edited it a little bit for the demo.

Demo
I am the parent div.

I am a child div within the parent div.

 

Continue reading →

How to find and replace text dynamically via JavaScript

March 7th, 2008  |  Published in javascript  |  7 Comments


This is a neat little script that demonstrates two things:

1) Find – If only the Find box is filled in, then the findMyText() JavaScript function will just perform a find for the div that is given. If there is a match, the text will be highlighted and marked in bold.

2) Find and Replace – If both the Find and Replace boxes are filled in, then the findMyText() JavaScript function will do just that.

Demo
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Find
Replacment

Continue reading →

Simulate a button click via JavaScript

March 5th, 2008  |  Published in javascript  |  19 Comments

There is a rare need for this type of functionality but I have found myself in a couple of situations where I needed it. Here is a quick demo of a button click that is simulated from another event handler. In this case, the button click is invoked by checking a checkbox.

Demo Check the box to simulate a button click

Continue reading →

JavaScript to select all or none of the checkboxes in a form

February 28th, 2008  |  Published in javascript  |  5 Comments


Here is a quick demo of the select all or none JavaScript function that automatically toggles all of your checkboxes in a given form.

Demo
My favorite programming/scripting language is:

Select All | None

JavaScript

Perl

PHP

C++

Continue reading →

Form verification via JavaScript

February 27th, 2008  |  Published in javascript  |  1 Comment


Are you looking for a simple way to verify a form that you have? The example below demonstrates some of the common techniques used in verifying a form. Test out the form by leaving at least one of the fields blank before you submit the form.

Demo
Username
Please fill in your username.

Email

Please fill in your email.

Continue reading →

Dynamically edit font styling of HTML content via JavaScript

February 24th, 2008  |  Published in javascript

The Document Object Model (DOM) allows for dynamic styling because it makes all HTML elements and attributes readily accessible using JavaScript. Here is a simple demo of how powerful this technology can be:

Demo
Hello world!

Continue reading →

How to dynamically add form elements via JavaScript

February 21st, 2008  |  Published in javascript  |  65 Comments



Not all forms are meant to be static. Sometimes, you want to allow the users to add certain parts of the form as they need them. Here is a nice example of dynamically adding inputs to your form as users need them. In addition, an input limit has been implemented in the script and it is set to 3.

Demo
Entry 1

Continue reading →

How to hide, show, or toggle your div

February 12th, 2008  |  Published in javascript  |  157 Comments

Are you trying to find a way to hide and show your content? The demo below shows a simple yet elegant way of toggling your content and toggling the control text via Javascript and styling.

Demo
Let’s use images! click image to expand/collapse div ==>

This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript.
Demo

show < == click here

peek-a-boo

Continue reading →

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets