Here is a couple of query string parsing functions I put together in Javascript today. This first one will parse the current query string and return an object with properties for each of the arguments in the query string.
<script type="text/javascript">
function parse_args() {
var args = new Object();
var query = window.location.search.substr(1).split('&');
var tmp = null;
for(var i = 0; i < query.length; i++) {
tmp = query.split('=');
args[tmp[0]] = tmp[1];
}
return args;
}
</script>
This second function will find an argument in the query string by name and then return the value, if it exists. If the argument is not found it will return false.
<script type="text/javascript">
function find_arg_value(name) {
var query = window.location.search.substr(1).split('&');
var tmp = null;
for(var i = 0; i < query.length; i++) {
tmp = query[i].split('=');
if(tmp[0] == name) {
return tmp[1];
}
}
return false;
}
</script>
One of the lesser known features of Cascading Style Sheets is the ability to apply more than one class to a single element. Browser support for this is pretty good and goes back at least as far as Internet Explorer 6. I needed to put this feature to use, so I did a few experiments on how it works and thought I would share my notes here.
To give an element more than one class you just separate the class names with spaces. Below is an example of a div with three classes.
<div class="one two three"></div>
A couple of things I found about using multiple classes are:
- The order of the classes makes no difference. class=”one two” is the same as class=”two one”. Standard inheritance applies and if the classes are at the same level of inheritance (i.e. both classes are defined in style tags) the class that is defined last will have its rules take priority.
- In Javascript, the className property returns all class names in a string (getAttribute(’class’) returns the same, doesn’t work in IE6).
- Also in Javascript if you are looking for a particular class it can be handy to use split to divide the className property into an array.
String(document.getElementById('test').className).split(' ')
You can see the example code in action by clicking here. Take a look at the source to see how the multiple classes interact and override each other the generate the final look of the div.
I found this code snippet in a four year old email that I had sent myself. This is the basic code layout that I use for form validation. What is nice about it is that it will parse the whole form and compile a list of all the form validation errors to present to the user at once, instead of presenting it to the user one field at a time and making them hit the submit button over and over again to get the form right.
<script type="text/javascript">
function verify() {
var valid = true;
var info = "Please correct the following:";
// Below are some example tests that can make the valid flag false and
// add text to the error message.
if(document.getElementById('name').value == "") {
info += "\n - enter your name";
valid = false;
}
if(document.getElementById('zip').value.length != 5 ||
document.getElementById('zip').value.match(/[^0-9]/g) !== null) {
info += "\n - zip must be five numbers";
valid = false;
}
// The above are just examples you can add as many tests as you want.
if(!valid) {
alert(info);
}
return valid;
}
</script>
The validation function maintains a flag that tracks whether any errors have been found. You can do as many tests on the form as you want and keep adding to the error message so the user can see everything that is wrong with the form all at once.
Lately I have been doing a lot work with passing data back and forth between Javascript and PHP and I often am working on arrays on the Javascript side and there is no easy native method to test whether an array contains a certain value. So I wrote my own.
function in_array(needle, haystack, strict) {
for(var i = 0; i < haystack.length; i++) {
if(strict) {
if(haystack[i] === needle) {
return true;
}
} else {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
You could also prototype it to be built in to the native Array object. You just have to tweak the code a little.
function in_array(needle, strict) {
for(var i = 0; i < this.length; i++) {
if(strict) {
if(this[i] === needle) {
return true;
}
} else {
if(this[i] == needle) {
return true;
}
}
}
return false;
}
Array.prototype.in_array = in_array;
// example usage
var test = new Array();
test.push('i');
test.push(1);
test.in_array('i'); // true
test.in_array('i', true); // true
test.in_array('b'); // false
test.in_array(1, true); // true
test.in_array('1', true); // false
The other day someone asked me how to validate a multiple select on a form in Javascript. They needed to check that the person filling out the form at least chose one option. This is what I came up with off of the top of my head.
Here is a basic multiple select.
<select id="color" multiple="multiple" size="5">
<option>Red</option>
<option>Orange</option>
<option>Yellow</option>
<option>Green</option>
<option>Blue</option>
</select>
Here is the Javascript function code that you can pass a reference to a select to and it will return true if one or more options are chosen, otherwise it will return false.
function multiselect_validate(select) {
var valid = false;
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
valid = true;
break;
}
}
return valid;
}
Here is an example of how you could call the above function on a select.
// referencing the select above by id
multiselect_validate(document.getElementById('color'));
The example above is a little limited in that it will only ensure that at least one option is chosen. It wont work if you need to check that at least two (or more) options are selected. This modified function can take an additional argument to specify how many options need to be selected.
function multiselect_validate(select, num) {
if(!num) {
num = 1;
}
var valid = false;
var found = 0;
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
found++;
if(found == num) {
valid = true;
break;
}
}
}
return valid;
}
This is a Javascript based password strength tester. It works really well and the code is available under the GPL.
http://www.passwordmeter.com
This is a function that will take a block of text and wrap hyperlink tags around anything that it recognizes as a link. It supports email addresses and anything that starts with http://, https:// or www.
It is implemented in Javascript but the regular expression code should be pretty universal.
function automagic_link(str) {
str = str.replace(/([^@ ]+)(@)([A-Za-z0-9.-]+)/gi, '$1@$3');
str = str.replace(/((http(s?):\/\/)|(www.))+([A-Za-z0-9./&=#?-~%;]+)/gi, 'http$3://$4$5');
return str;
}
This is a pretty good list (although not exhaustive) of examples of where an attacker could implant code to compromise your website. It is a nice list because they also show which browsers the various injection attacks work in.
Here is the link to the sheet.
http://ha.ckers.org/xss.html
I wrote this the other day and thought it was worth posting here. It is Javascript that will allow you to float a div that moves up and down as the user scrolls the webpage in the browser window. It will speed up and animate faster if the user scrolls quickly from spot to spot or slower if they scroll slowly.
Here is the Javascript.
<script type="text/javascript">
/**
* Animates a floated div to move up and down with the scrolling of the page.
*
* More details at http://www.finefrog.com/2007/12/14/animated-floating-sidebar/
*
* @author Jordon Mears <jordoncm at gmail dot com>
*/
function animate_box() {
var offset = 0; /* set this to the starting margin-top in the css */
var element = document.getElementById('animate_box');
if(element) {
var top = Number(String(element.style.marginTop).substring(0, String(element.style.marginTop).indexOf('px')));
var difference = (document.documentElement.scrollTop + offset) - top;
if(difference > 0) {
element.style.marginTop = (top + Math.abs(Math.ceil(difference / 10))) + 'px';
} else if(difference < 0) {
element.style.marginTop = (top - Math.abs(Math.ceil(difference / 10))) + 'px';
}
}
}
window.setInterval(animate_box, 50);
</script>
Here is the div. Since it is just a float, you can easily embed it inside other elements.
<div id="animate_box" style="float: right;">I am an animated div that scrolls with the browser window.</div>
Click here to see an example of it at work.
It works in all standard compliant browsers and Internet Explorer 6+ (maybe even older).
You are welcome to use this for whatever you want; I just ask that you retain the credits (and maybe leave me a comment).