Dropdown must use both onChange and onKeyPress events

Bear in mind that when writing JavaScript / jQuery code for handling user changes made to dropdown boxes, you must program your website reaction not only to onChange but also to onKeyPress events. Why? There is a rare situation, where user selects value by clicking dropdown and then using keyboard’s cursor up or cursor down keys. onKeyPress event will be fired in this situation instead of onChange event. And desired effect won’t work, if you put it only to onChange event handler.

In jQuery code change is simple. Instead of using .change event:

[code language=”javascript”]
$(".active-text-field").change(function()
{
var dep = $("#RegForm_departament").val();
var typ = $("#RegForm_type").val();
var pat = $("#RegForm_patient").val();

dropCookies(calculatePrice());

var url = "?departament=" + dep + "&type=" + typ + "&patient=" + pat;

window.location.href = url;
})
[/code]

you should use .bind and bind two events:

[code language=”javascript”]
$(".active-text-field").bind("change keypress", function()
{
var dep = $("#RegForm_departament").val();
var typ = $("#RegForm_type").val();
var pat = $("#RegForm_patient").val();

dropCookies(calculatePrice());

var url = "?departament=" + dep + "&type=" + typ + "&patient=" + pat;

window.location.href = url;
});
[/code]

In pure JavaScript you probably need to move your code to a function and attach call to it to both onclick="" and onkeypress="" attributes in your dropdown HTML element.

Leave a Reply