Update! This code still works but I encourage you to try my new library "Better DNI" that I hosted on Github. Try it now: https://better-dni.singuerinc.com/
Since this is my most viewed post I wanted to update a bit and make it more "reactive". If you want to generate some valid NIF or NIE for testing, you could use the following tool:
https://jsfiddle.net/singuerinc/n5w2nsa9/14/
But, if what you want is validate some DNI you should use this little function I've made some time ago. I've used on this demo Vue.js, a new Javascript library that allows me to make a quick reactive prototype: