disable button when textfields are empty

Ayub picture Ayub · Aug 15, 2011 · Viewed 20.8k times · Source

hi im a beginner to programming and have been stuck on this task for ages and seem to be getting nowhere.

basically i have several textfields that generates the input information on a different page when the user presses a button. i would like the button to be disabled until all text fields are filled with information.

so far i have this:

    - (void)textFieldDidEndEditing:(UITextField *)textField
{
    // make sure all fields are have something in them

if ((textfbookauthor.text.length  > 0)&& (textfbookedition.text.length > 0)&& (textfbookplace.text.length > 0)&& (textfbookpublisher.text.length > 0) && (textfbookpublisher.text.length > 0) && (textfbooktitle.text.length > 0)  && (textfbookyear.text.length > 0)) {
        self.submitButton.enabled = YES;
    }
    else {
        self.submitButton.enabled = NO;
    }
}

the problem is the 'submitButton' is coming up with an error, what needs to go in its place? i tried to put my button 'bookbutton'in it instead but its not working.

this is my function for the 'generate' button

    -(IBAction)bookbutton:(id)sender;
{
    NSString* combinedString = [NSString stringWithFormat:
                                @"%@ %@ %@.%@.%@:%@.", 
                                textfbookauthor.text,
                                textfbookyear.text,
                                textfbooktitle.text,
                                textfbookedition.text,
                                textfbookplace.text,
                                textfbookpublisher.text];
    BookGenerate*bookg = [[BookGenerate alloc] init];
    bookg.message = combinedString;
    bookg.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:bookg animated:YES];
    [BookGenerate release];
}

if anybody knows how i can make it work or what i need to add please help.

thanks in advance

Answer

JonasG picture JonasG · Aug 15, 2011

Make an Outlet for every UITextField and create an IBAction in your .h:

IBOutlet UITextField *textField1;
IBOutlet UITextField *textField2;
IBOutlet UITextField *textField3;
IBOutlet UIButton *button

- (IBAction)editingChanged;

Connect all the outlets and connect the IBAction to every textfield with editingChanged:

 - (IBAction)editingChanged {
    if ([textfield1.text length] != 0 && [textfield2.text length] != 0 && [textfield3.text length] != 0) {
         [button setEnabled:YES];
     }
     else {
         [button setEnabled:NO];
     }
 }

Note that you can also use [textfield.text isEqualToString:@""] and put a ! in front of it (!means 'not') to recognize the empty textField, and say 'if the textField is empty do...'

And:

- (void)viewDidLoad {
    [super viewDidLoad];
    [button setEnabled:NO];
}