Random Snippets

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

About: Knix

Knix
Profile:

Building websites has sort of become a hobby of mine. During the course of my work, I have created some snippets of code that I hope prove useful to other developers.

Website

http://

Contact:

Email Knix

Posts by Knix

Sorting 2D associative arrays in PHP

Jul 13, 2009

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
(
[...]

Read | No Comments | Tags: php

Dynamic or on-the-fly percentage calculations with JavaScript

Jul 12, 2009

function calculatePercentage (oldval, newval) {
percentsavings = ((oldval – newval) / oldval) * 100;
document.getElementById(“results”).innerHTML = Math.round(percentsavings*100)/100;
}

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

Demo
MSRP (in dollars)

Sale Price (in dollars)

You have saved 50 %

Read | No Comments | Tags: javascript

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

Apr 8, 2009

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 [...]

Read | 4 Comments | Tags: javascript

How to randomly order or select rows in a MySQL query

Oct 28, 2008

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 [...]

Read | No Comments | Tags: mysql

How to convert MySQL timestamp to PHP date type

Oct 5, 2008

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 />";
}

Read | 5 Comments | Tags: mysql · php

How to count values with MySQL queries

Oct 5, 2008

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

Read | 13 Comments | Tags: mysql

How to confirm or prompt user for input via JavaScript

Jun 26, 2008

function removeYellowBox() {
var parentBox = document.getElementById(‘parentBox’);
var yellowBox = document.getElementById(‘yellowBox’);
parentBox.removeChild(yellowBox);
}

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 [...]

Read | No Comments | Tags: javascript

How to find and access parent nodes via JavaScript

Jun 26, 2008

function findParentNode(parentName, childObj) {
var testObj = childObj.parentNode;
var count = 1;
while(testObj.getAttribute(‘name’) != parentName) {
alert(‘My name is ‘ + testObj.getAttribute(‘name’) + ‘. Let\’s try moving up one level to see what we get.’);
[...]

Read | No Comments | Tags: javascript

How to loop through checkboxes or radio button groups via JavaScript

May 15, 2008

function loopForm(form) {
var cbResults = ‘Checkboxes: ‘;
var radioResults = ‘Radio buttons: ‘;
for (var i = 0; i < form.elements.length; i++ ) {
if (form.elements[i].type == ‘checkbox’) {
[...]

Read | 7 Comments | Tags: javascript

How to create your own customized calculator via JavaScript

Apr 26, 2008

function calculate(equation) {
var answer = eval(equation);
document.getElementById(’screen’).value = answer;
}
function pushButton(buttonValue) {
if (buttonValue == ‘C’) {
document.getElementById(’screen’).value = ”;
}
else {
[...]

Read | 8 Comments | Tags: javascript

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

Apr 14, 2008

function addContent(divName, content) {
document.getElementById(divName).innerHTML = content;
}
function setCookie(c_name,value,expiredays) {
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ “=” +escape(value)+((expiredays==null) ? “” : “;expires=”+exdate.toGMTString());
}
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + “=”);
[...]

Read | 9 Comments | Tags: javascript

How to validate email format via JavaScript

Apr 1, 2008

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:

Read | 11 Comments | Tags: javascript

How to dynamically remove/delete elements via JavaScript

Mar 26, 2008

function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert(“The parent div cannot be removed.”);
}
else if (document.getElementById(childDiv)) {
var [...]

Read | 25 Comments | Tags: javascript

How to find and replace text dynamically via JavaScript

Mar 7, 2008

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 – [...]

Read | 7 Comments | Tags: javascript

Simulate a button click via JavaScript

Mar 5, 2008

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 [...]

Read | 19 Comments | Tags: javascript

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

Feb 28, 2008

function selectToggle(toggle, form) {
var myForm = document.forms[form];
for( var i=0; i < myForm.length; i++ ) {
if(toggle) {
myForm.elements[i].checked = “checked”;
[...]

Read | 5 Comments | Tags: javascript

Form verification via JavaScript

Feb 27, 2008

function verifyForm(form) {
var userName = form.name.value;
var userEmail = form.email.value;
var success = 1;
if (!userName) {
document.getElementById(“usernameMsg”).style.display = “”;
form.name.style.backgroundColor = “yellow”;
[...]

Read | 1 Comment | Tags: javascript

Dynamically edit font styling of HTML content via JavaScript

Feb 24, 2008

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!

Read | No Comments | Tags: javascript

How to dynamically add form elements via JavaScript

Feb 21, 2008

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 [...]

Read | 65 Comments | Tags: javascript

How to hide, show, or toggle your div

Feb 12, 2008

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.

function toggle() {
var ele = document.getElementById(“toggleText”);
var text = document.getElementById(“displayText”);
if(ele.style.display == “block”) {
ele.style.display = “none”;
text.innerHTML = [...]

Read | 157 Comments | Tags: javascript

next page

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