Determine if a value is an option in a select element with jQuery

To determine if an html select box contains a given value as an option, in jQuery you can try to select the option and see if it exists:

if($("#id option[value='someval']").length != 0) {
  // it exists!
}

That’s it! Have fun!

String contains an invalid character

Wow, it’s been over a month since I posted anything on here. I must be slacking big time! Well, here’s a goody I found recently…

I was playing around with a third party JavaScript library the other day. Not really using it for anything, just wanted to see how it worked. Anyway, the first time I fired up the demo that came with it, it doesn’t work and this shows up in firebug:

String contains an invalid character

Inspecting a bit further I find a bunch of gems like this:

var div = document.createElement("<div name='hello'>");

Wait, what? WTF is that? That’s not how createElement is used! It seems yet again, Internet Explorer deviates drastically from the standard and lets you do ugly nasty things like that. So the code above only works in Internet Explorer. It is broken everywhere else. As an example, the following is IE only:

<html>
  <head>
    <script type="text/javascript">;
    function load()
    {
      var body = document.getElementsByTagName("body")[0];
      var div = document.createElement("<div name='hello'>");
      div.innerHTML = "Hello, world!";
      body.appendChild(div);
    }
    window.onload = load;
    </script>
  </head>
  <body>
  </body>
</html>

This is also IE only:

<html>
  <head>
    <script type="text/javascript">
    function load()
    {
      var body = document.getElementsByTagName("body")[0];
      var div = document.createElement("<div>");
      div.setAttribute("name", "hello");
      div.innerHTML = "Hello, world!";
      body.appendChild(div);
    }
    window.onload = load;
    </script>
  </head>
  <body>
  </body>
</html>

This is the correct way to do it!

<html>
  <head>
    <script type="text/javascript">
    function load()
    {
      var body = document.getElementsByTagName("body")[0];
      var div = document.createElement("div");
      div.setAttribute("name", "hello");
      div.innerHTML = "Hello, world!";
      body.appendChild(div);
    }
    window.onload = load;
    </script>
  </head>
  <body>
  </body>
</html>

Note the use of innerHTML. This was originally another Microsoft-ism. However, it’s been adopted by all major browsers and is now officially in HTML5 so I don’t feel quite so dirty for using it!

missing ] after element list parsing JSON

I was working on a little web application front end submitting a form and processing a result asynchronously using jQuery. I wrote a little JavaScript snippet that looks something like the following:

$.post( "submitForm.jsp", theForm.serialize(), function(data) {
  var res = eval('(' + data + ')');
  // do something with the result
});

Yeah, I know, eval() probably isn’t the best choice here but we need to support IE7 which doesn’t support JSON.parse natively. Anyway, after submitting I get the following error:

error: missing ] after element list parsing JSON

Turns out that jQuery will try to figure out if the result is JSON and parse it automatically. In this case data is already a JavaScript object and not a JSON string waiting to be parsed.

container.getElementsByTagName is not a function

I was setting up DokuWiki the other day to play around with. I want to use it as a kind of note pad of sorts to document some of my work and ideas and keep them accessible. As I was tweaking things here and there things started to get a little broken. In particular, the cool editing toolbar over the edit box when editing topics disappeared. Looking at the DokuWiki faq it seems the most likely cause is broken JavaScript somewhere so I opened up FireBug to see what was happening. This is what I found:

container.getElementsByTagName is not a function
   var collection = container.getElementsByTagName(tagName);

Well, that looks like a valid function for a DOM element so why would it not be defined? This error is occurring on line 2155 of ASCIIMathML.js (2.0.2) in the function called getElementsByClass(). This function takes three parameters, container, tagName, and clsName. So I set a break point and check some of the parameters. Right away I see that the container parameter is actually being given a string that actually looks like a class name. Until recently, browsers didn’t supply a native getElementsByClass() function[1] so libraries that needed it provided their own implementation. It seems this implementation is overriding another implementation that does take the class name as a first parameter instead of a DOM element.
ASCIIMathML.js actually only calls this function twice so I opted for the simple solution of find/replace in ASCIIMathML.js and renamed the function to something simple like amGetElementsByClass(). With that change, the error is gone and my toolbar is back.
[1] JavaScript now has a native getElementsByClassName() method supported by Firefox 3 and up, IE9 (not 7 or 8!) Safari, Chrome and Opera.

]]>

JavaScript to Disable Form Submit with Enter Key

I ran into an issue the other day where I needed to disable form submission when the enter key was pressed. To fix this you need to add a hander for onKeyPress for the <body>. This will disable any effect by the Enter key for the entire page.

onKeyPress for the <body>. This will disable any effect by the Enter key for the entire page.

<script language="JavaScript">
function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;
     else
          key = e.which;
     return (key != 13);
}
</script>
<body onKeyPress="return disableEnterKey(event)">

If you want to disable form submission for a particular input field, add the onKeyPress handler of the input field:

<input type="text" name="foo" onKeyPress="return disableEnterKey(event)" >

]]>

Impressive!

Fabrice Bellard, the initiator of the QEMU emulator, wrote a PC emulator in JavaScript. You can now boot Linux in your browser, provided it is recent enough. You need Firefox 4 or Google Chrome 11. Sorry no IE. Check it out here.]]>

Updated Maze Generation script

I’ve created an updated version of the maze generation script to create somewhat more difficult mazes. This version uses a depth-first search algorithm to randomly link adjacent cells. Once all the cells have been linked there is only one path from one cell to any other cell in the maze.

The algorithm first randomly chooses a cell and pushes it onto a stack. From that current cell, it chooses a random adjacent cell and links them. The chosen adjacent cell is then pushed on the stack and becomes the new current cell. This process repeats until there are no more adjacent cells that can be chosen. Once no more adjacent cells can be chosen for the current cell, it is popped from the stack and the new top cell becomes the current. It is then checked for another available adjacent cell. Again, if there are no more adjacent cells that can be chosen, it is popped. Once the stack is empty all the cells are linked with exactly one path from one cell to any other cell. A random enter and exit point is chosen and the maze can be rendered.

The depth first search algorithm generates somewhat more difficult mazes than the original minimum spanning tree algorithm I used since it generates longer continuous paths before creating a branch. When the new branch reaches an existing path it creates a dead end. Given that the branches tend to be much longer you may end up having to follow the branch and many sub-branches before discovering it is in fact a dead end. With the minimum spanning tree algorithm the branches tended to be of a similar length and don’t typically wander far from the solution path.

The maze generator requires a browser that supports HTML 5 and the ‘canvas’ element. This is basically any modern browser except Internet Explorer. (IE users can try to use excanvas.js but you’re on your own.) You can try it out here. You can also download the javascript for it here.

Useful resources:

Sudoku in JavaScript

This is a Sudoku puzzle generator and solver. This program provides two generation algorithms, a solver and methods to update and check the state of the puzzle. I had found a JavaScript Sudoku at https://www.dhtmlgoodies.com/scripts/game_sudoku/game_sudoku.html which I thought was pretty cool, however, it didn’t create very good puzzles. Most had more than one solution and if you didn’t find the solution it chose as a the final solution, you would never finish the game. I started thinking about how you would actually create a working Sudoku puzzle. This is my first attempt. The puzzle is generated using the solver to solve an empty Sudoku board. It implements a backtracking algorithm in which it randomly selects numbers to try in each cell. It starts with the first cell and picks a random number. If the number works in the cell, it recursively chooses the next cell and starts again. If all the numbers for a cell have been tried and none work, a number chosen for a previous cell cannot be part of the solution so we have to back up to the last cell and choose another number. If all the numbers for that cell have also been tried, we back up again. This continues until a value is chosen for all 81 cells. (The actual implementation is pretty much what is described here though it does use some optimizations and tricks so it isn’t too painfully slow. If you’re interested check out the source which is heavily commented.) Once the board is filled in, values are removed until no more values can be removed without creating a puzzle with more than one solution.  Actually, Medium and Hard are guaranteed to have only a single solution. Easy uses a naive algorithm similar to that used at the dhtmlgoodies.com link above which may have more than one solution. Don’t worry though, if you find a valid solution the game will finish. The game can be found here. The source contains very detailed comments describing how the algorithm works. The source can be viewed here. Have fun. Send any comments, bugs, contributions to djrager@fourthwoods.com

Useful resources:

]]>

Maze Generation script

Update: This script has been updated as of this newer article.

So, I thought it would be cool to create a program for my daughter that would generate mazes that she could print out and solve. Originally I was going to create a Windows program but I didn’t really feel like dealing with the windows GDI and printer quirks. Luckily for me, and all the other web developers in the world, web browsers happen to have printer support built in! I created a random maze generator in javascript, based on a modified version of Kruskal’s algorithm. This code is modeled roughly on the fast_maze program that can be found at https://nehe.gamedev.net written by smart_idiot. When I wanted to learn several years ago how maze generators worked, this was the algorithm learned. The maze generator requires a browser that supports HTML 5 and the ‘canvas’ element. This is basically any modern browser except Internet Explorer. (IE users can try to use excanvas.js but you’re on your own.) You can try it out here. You can also download the javascript for it here. Have fun.