JavaScript


Enter key fires click event on form submit button

I ran into an odd situation today where pressing the enter key in a form would submit the form as if I’d clicked the submit button. I captured the event and inspected the “which” and keyCode and they both said “1”, which is the left click of a mouse (13 is the enter key). Apparently pressing the enter key also fires the click event of the submit button in a form! This is something browsers are starting to implement now as the html5 spec says the following:

“User agents may establish a button in each form as being the form’s default button. This should be the first submit button in tree order whose form owner is that form element, but user agents may pick another button if another would be more appropriate for the platform. If the platform supports letting the user submit a form implicitly (for example, on some platforms hitting the “enter” key while a text field is focused implicitly submits the form), then doing so must cause the form’s default button’s activation behavior, if any, to be run.”

I need to separate the enter key from the click action of the submit button, so the code below will do the trick.

$('form').bind("click keypress", function(e) {
	var keyCode = e.which || e.keyCode;
	if (keyCode == 13) {
		//alert("ENTER pressed");
 
		/*
		 * prevent the next automagic action that occurs... a click 
		 * action on the form's submit button.
		 */
		e.preventDefault();
	} else {
		var sender = e.target;
		if (sender.type == "submit") {
			//alert("Submit button " + sender.id + " clicked");
			e.preventDefault();
			submitButtonHandler();
		} else {
			//some other keypress
		}
	}
	return true;
});

Cloning an array with JavaScript

I had a need to clone an array with JavaScript. There appears to be a number of different ways to do it, including writing your own function. All of these solutions below will just create a reference to the original array:

var newArray = myArray.slice(0);
var newArray = myArray.concat([]);
var newArray = clone(myArray);

A popular answer using jQuery is the following:

var newArray = jQuery.extend(true, {}, myArray);

However, this solution will return an object and you cannot get the length of an object like you can an array.

To return an array, we change the curly braces to square brackets like so:

var newArray = jQuery.extend(true, [], myArray);

This is the solution that works.


How to use date on google scatter chart 2

The google visualization api limits you to using numeric values for both the X and Y axis, but there is a trick you can do with the google image chart api to covert the value to a date as below. Use JavaScript’s Date() object for the conversion. It would be nice if we could just specify the column as a string like data.addColumn(‘string’, ‘Date’), but the chart still will not accept the string. It will accept a date object though. The next task is to format the date string, it appears google accounts for with the google.visualization.DateFormat method, but it does not work. In the end, I had to accept the formatting provided by the chart of “15 Nov 2011” as the format for a “datetime” column, which looked better than the format displayed for a “date” column.

    var data = new google.visualization.DataTable();
    data.addColumn('datetime', 'Date');
    data.addColumn('number', 'Quantity');
    data.addRow([new Date(2011, 0, 1), 10])
    data.addRow([new Date(2011, 1, 1), 15])
    data.addRow([new Date(2011, 2, 1), 12])
    data.addRow([new Date(2011, 3, 1), 18])
    data.addRow([new Date(2011, 4, 1), 17])
    data.addRow([new Date(2011, 5, 1), 19])
    data.addRow([new Date(2011, 6, 1), 25])
    data.addRow([new Date(2011, 7, 1), 18])
    data.addRow([new Date(2011, 8, 1), 24])
    data.addRow([new Date(2011, 9, 1), 28])
    data.addRow([new Date(2011, 10, 1), 27])
    data.addRow([new Date(2011, 11, 1), 34])
 
 
    // Create and draw the visualization.
    var chart = new google.visualization.ScatterChart(
        document.getElementById('chart'));
    chart.draw(data, {title: 'Test',
                      width: 600, height: 400,
                      vAxis: {title: "cr"},
                      hAxis: {title: "time"}
                      }
              );

Reset button doesn’t work on selected=”selected” form element

Using Zend_Form, it generated a select element where the selection option had an attribute of selected=”selected” instead of just adding “selected” to the element. The form’s reset button no longer works on this element. Because it’s being generated, I can’t simply change how the attribute is specified in the element, so I used some JavaScript to reset all the form elements when a reset button is clicked. If you have multiple forms and multiple reset buttons, then you’ll need to modify this to point at a specific form’s elements rather than all on a page.

 $("input:reset").click(function(event) {
	 event.preventDefault();
 
	// Whitelist of fields to minimize unintended side effects.
	$(':text, :password, :file, SELECT', 'form').val('');
 
	// De-select any checkboxes, radios and drop-down menus
	$(':input').removeAttr('checked').removeAttr('selected');
	$("select").find('option').removeAttr("selected");
 });

Scriptaculous Ajax.autocompleter stop preselect of first option item 1

I have this search feature on the search input of my sites, but was annoyed when I’d hit the enter button the keyboard to submit the search after the autocomplete items were visible. Instead of submitting the form as I desired, the first autocomplete option was entered into the input and then the form was submitted.

To disable the pre selection of the first result item in the autocomplete, do the following:

In controls.js of the Scriptaculous library, on line 286: change “this.index = 0;” to “this.index = -1;”