简体   繁体   中英

Drupal PHP Form Submit On Enter

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.

我通过在要触发提交事件的文本字段上添加以下代码来实现此目的:

$form['field_name']['#attributes']['onkeypress'][] if (event.keyCode == 13) {jQuery('.submit-selector').mousedown();}

这为我工作:

$form[FORM_ITEM]['#attributes']['onkeypress'][]="jQuery('input').keydown(function(e) {if (e.keyCode == 13) {e.preventDefault(); jQuery('#edit-submit').mousedown();}});";

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM