user153923
user153923

Reputation:

Detecting Textarea Object in jQuery

I've got a bit of jQuery to suppress a carriage return when customers are filling out our forms:

$('form.eForm:not(.suppress-submit-on-enter-key-disabled) :not(:button, :submit)').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

However, it has also managed to suppress the carriage returns on our Comment boxes.

It seemed simple enough to add a textarea checker like the existing code has to check for :not (:button, :submit):

$('form.eForm:not(.suppress-submit-on-enter-key-disabled) :not(:button, :submit, :textarea)').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

Whoops! :not (:button, :submit, :textarea) didn't work, because it seems that textarea is not defined for this part of jQuery.

How do others detect these TextArea controls?

Update:

One of the people who posted an answer on here turned out to have the solution.

The eForm class that all of our forms are generated from was somehow catching this.

It took my manager and I a couple of hours hammering on this to get it resolved, but in the end all I needed to do was to only handle events from an Input control.

Here is our end result:

$('form.eForm:not(.suppress-submit-on-enter-key-disabled) :input:not(:button, :submit, textarea)').keypress(function (e) {
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

Special thanks to Khawer Zeshan for providing that Fiddle. It proved to me that there was something deeper wrong with my code.

Upvotes: 0

Views: 114

Answers (2)

Ayman Bedair
Ayman Bedair

Reputation: 937

I recently had the same concern in mind, and created this very simple jQuery plugin for it

https://github.com/aymanrb/jquery-tabable-required

Upvotes: 1

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

Why dont you use id for single textarea and class name for multiple selectors?

For only one textarea:

$('#textareaid').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

For multiple fields use the class name and apply the same class for those fields:

$('.textareaClass').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

FIDDLE

Upvotes: 4

Related Questions