rails 3 + jquery enabling submit button on text field change
I have a simple form with one text field and a submit button. Upon clicking submit, I make an ajax request which returns some jquery to execute. In this jquery, I disable the submit button of the form and enable the button if the text field changes. Following is the code I am using:
$("#my_form input[type=submit]").attr("disabled","true");
$("#my_form #my_form_text").change(function()
{
$("#my_form input[type=submit]").r开发者_运维问答emoveAttr("disabled");
});
The issue is that I want the submit button to be enabled as soon as I change the text field. The submit button is enabled after I change the text field AND move the cursor out of the text field. Is there a way the submit button gets enables as soon as I make a modification in the text field (even with my cursor still being in the text field)?
Thanks.
Bind the textfield to the keyup event. Each time a key is pressed, you'll know the text is changing.
http://api.jquery.com/keyup/
$('textfield').keyup(function() {
alert('text changed');
});
You might want to take a look at jQuery’s keyup
method: http://api.jquery.com/keyup/
In the event handler, check whether there has been any actual input as a result of the keyup
event rather than, say, the user having only pressed the delete key.
Careful though: A user might still copy and paste text using the mouse and none of the two events would fire.
This accommodates all cases I can think of right now:
var changeHandler = function (e) {
if (this.value) $("input[type=submit]").removeAttr("disabled");
};
$("input[type=text]").keyup(
changeHandler
).change(
changeHandler
).mousemove(
changeHandler
);
See: http://jsfiddle.net/E86T9/
精彩评论