views:

3422

answers:

4

i have this hmtl:

<input type="text" name="textField" />
 <input type="submit" value="send" />

how can i do something like this: -when the text field is empty the submit should be disabled(disabled="disabled") -when something is typed in the text field to remove the disabled attribute -if the text field becomes empty again(the text is deleted) the submit button should be disabled again

i tried something like this

$(document).ready(function(){
     $('input[type="submit"]').attr('disabled','disabled');
     $('input[type="text"]').change(function(){
            if($(this).val != ''){
               $('input[type="submit"]').removeAttr('disabled');
            }
     });
 });

..but it doesn't work.any ideas? thanks

+2  A: 
$(function() {
  $(":text").keypress(check_submit).each(function() {
    check_submit();
  });
});

function check_submit() {
  if ($(this).val().length == 0) {
    $(":submit").attr("disabled", true);
  } else {
    $(":submit").removeAttr("disabled");
  }
}
cletus
great, thanks :)
kmunky
yap it works! but..one question though...can you explain this : $(":text").keypress(check_submit).each(function() { check_submit(); });thanks
kmunky
+2  A: 

The problem is that the change event fires only when focus is moved away from the input. Try using keypress instead:

$(document).ready(function(){
     $('input[type="submit"]').attr('disabled','disabled');
     $('input[type="text"]').keypress(function(){
            if($(this).val != ''){
               $('input[type="submit"]').removeAttr('disabled');
            }
     });
 });
Eric Palakovich Carr
ok, but the problem is when i delete the last letter i have to press even one more time to capture the empty val and disable my button, cause when i press the backspace to delete the last letter my field is still populated , so my keypress is captured and then the letter is deleted. so...how should i do it right?
kmunky
Oh, my apologies for not testing the code first. If you replace keypress with keyup does that help?
Eric Palakovich Carr
yup it does, thanks again :)
kmunky
A: 

eric, your code did not seem to work for me when the user enters text then deletes all the text. i created another version if anyone experienced the same problem. here ya go folks:

$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
    if($('input[type="text"]').val() == ""){
        $('input[type="submit"]').attr('disabled','disabled');
    }
    else{
        $('input[type="submit"]').removeAttr('disabled');
    }
})
Archie1986
A: 

What if the user copies text from somewhere and pastes in text field using the mouse only. The button is not enabled.. What can be done in this case ?

Kunday