Reputation: 5831
I am trying to troubleshoot a PHP form within a Drupal 7 site. At the moment, the form can only be submitted if the user clicks the button. I would like to enable submission with "Enter" key. How can I do this?
Here is the relevant code:
$form['search']['search_button'] = array(
'#type' => 'button',
'#value' => 'Search',
'#ajax' => array(
'callback' => 'ajax_search_callback',
// 'wrapper' => 'search-results',
'wrapper' => 'search',
'method' => 'replace',
'effect' => 'fade',
'event' => 'click',
),
);
I suspect that I need to change 'event' field or add another field.
Upvotes: 2
Views: 2276
Reputation: 91
I implemented this by adding this piece of code on textfield on which i want to trigger submit event:
$form['field_name']['#attributes']['onkeypress'][] if (event.keyCode == 13) {jQuery('.submit-selector').mousedown();}
Upvotes: 3
Reputation: 389
This worked for me:
$form[FORM_ITEM]['#attributes']['onkeypress'][]="jQuery('input').keydown(function(e) {if (e.keyCode == 13) {e.preventDefault(); jQuery('#edit-submit').mousedown();}});";
Upvotes: 1
Reputation: 126
I'm not an expert in JS, but this is how i would have tackled the issue myself.
I didn't test it, but I suggest adding something like the following statement in your js file
$( document ).ready(function() {
$( "#target" ).keypress(function() {
if ( event.which == 13 ) {
$('my_form').submit();
}
});
});
Basically, you look for the keypress event 13, then you submit your form.
I hope your form doesn't have any textarea tags, because you might face some user issues.
EDIT: Where to add the Javascript?
I assume you are writing a custom module to generate your form, so you can add a path to the .info file of your module or use the function drupal_add_js("your_path_to_js_file"); which is probably a better solution here.
I hope it helps.
Cheers
Upvotes: 0
Reputation: 21
You need to add the keypress attribute to the ajax array and set it to TRUE. It is explained in the form api documentation, here.
EDIT : The first solution works only for one single input field. To add keypress event on the form, you must add an "onkeypress" attribute to the form by adding it in the attributes array:
$form['#attributes']['onkeypress'] = 'if(event.keyCode==13){this.form.submit();}';
Where 13 is the keyCode for Enter (or return for a mac).
I don't know if it's the cleanest solution, but it should work.
Upvotes: 1