Difficulty with jQuery and input keydown event
Posted
by
Rosarch
on Stack Overflow
See other posts from Stack Overflow
or by Rosarch
Published on 2011-01-17T19:47:09Z
Indexed on
2011/01/17
19:53 UTC
Read the original article
Hit count: 129
I am making a simple JavaScript enhanced list. I want it to be a list of inputs, each with an 'Add' and 'Remove' button. If the user clicks 'Add', a new li
will be added. If the user clicks 'Remove', that li
will be removed.
It works fine, except for hitting "enter" in an <input>
. Currently, it always causes the Remove.click
event handler to fire, unless there's only one item in the list. I'm not sure why. How can I suppress this?
Here is the complete jQuery. My attempt to fix the "enter" issue is commented out, and it doesn't work. I suspect that I could be designing this code better; if you see an improvement I'd love to hear it.
function make_smart_list(list)
{
var ADD_CLASS = 'foo-widget-Add';
var REMOVE_CLASS = 'foo-widget-Remove';
var jq_list = $(list);
jq_list.parents('form').submit(function() {
return false;
});
function refresh_handlers() {
jq_list.find(sprintf('.%s, .%s', REMOVE_CLASS, ADD_CLASS)).unbind('click');
// jq_list.find('input').unbind('submit');
//
// jq_list.find('input').submit(function() {
// var jq_this = $(this);
// var next_button = jq_this.nextAll('button');
// if (next_button.hasClass(ADD_CLASS)) {
// next_button.nextAll('button').click();
// return;
// }
//
// if (next_button.hasClass(REMOVE_CLASS)) {
// return false;
// }
//
// });
jq_list.find("." + REMOVE_CLASS).click(function() {
var jq_this = $(this);
jq_this.parent().remove();
refresh_handlers();
return false;
});
jq_list.find("." + ADD_CLASS).click(function() {
var jq_this = $(this);
if (jq_this.prevAll('input').val() == '') {
return;
}
jq_this.parent().clone().appendTo(jq_this.parent().parent());
jq_this.parent().next().find('input').val('').focus();
jq_this.removeClass(ADD_CLASS).addClass(REMOVE_CLASS);
jq_this.text('Remove');
refresh_handlers();
return false;
});
}
refresh_handlers();
}
(sprintf
is another script I have.)
© Stack Overflow or respective owner