$('form :input[type="text"]').live('keyup', function() {
var val = $.trim(this.value); // this.value is faster than $(this).val()
$('form .create-playlist-button').prop('disabled', val.length == 0);
});
DEMO
Here, I used .prop()
instead of .attr()
, according to jQuery doc .prop()
should be use. I also used .trim()
for removing the whitespace from the beginning and end of value.
About your code
In your code you used $('form :input[type="text"]')
two times, one for bind event and one to getting the value of text field. But that is not necessary, because within keyup
event handler function this
will refers to that input
element on which keyup
event binded.
If you sometime need to use any selector multiple times for any purpose it will be better to cache that in a variable and reuse that variable. Just for example:
var input = $('form :input[type="text"]');
input.on('click', function() {
alert( this.value );
input.addClass('something');
});
If would be better if you use .on()
instead of .live()
for delegate event handler, because .live()
has been deprecated.
You can use .on()
like following:
$('form').on('keyup', ':input[type="text"]', function() {
var val = $.trim(this.value);
$('form .create-playlist-button').prop('disabled', val.length == 0);
});
Note
Syntax of .on()
for delegate event handling is like:
$(staticContainer).on( eventName, target, handlerFunction )
Here, staticContainer
point to an element which belong to DOM at page load, i.e which is not dynamic and also container of target
on which you want to bind your event.
Just for some more go here