[英]Drupal PHP Form Submit On Enter
I am trying to troubleshoot a PHP form within a Drupal 7 site. 我正在尝试对Drupal 7站点内的PHP表单进行故障排除。 At the moment, the form can only be submitted if the user clicks the button. 目前,仅当用户单击按钮时才能提交表单。 I would like to enable submission with "Enter" key. 我想使用“ Enter”键启用提交。 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. 您需要将keypress属性添加到ajax数组并将其设置为TRUE。 It is explained in the form api documentation, here . 这是形式的API文档中解释说, 这里 。
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: 要在表单上添加keypress事件,必须通过在属性数组中添加“ onkeypress”属性到表单:
$form['#attributes']['onkeypress'] = 'if(event.keyCode==13){this.form.submit();}';
Where 13 is the keyCode for Enter (or return for a mac). 其中13是Enter的keyCode(或对于mac来说,是return)。
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. 我不是JS方面的专家,但是这就是我本人要解决的问题。
I didn't test it, but I suggest adding something like the following statement in your js file 我没有对其进行测试,但建议您在js文件中添加类似以下语句的内容
$( 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. 基本上,您查找按键事件13,然后提交表单。
I hope your form doesn't have any textarea tags, because you might face some user issues. 我希望您的表单没有任何textarea标签,因为您可能会遇到一些用户问题。
EDIT: Where to add the Javascript? 编辑:在哪里添加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"); 我假设您正在编写一个自定义模块来生成表单,因此可以将路径添加到模块的.info文件,或使用函数drupal_add_js(“ your_path_to_js_file”); which is probably a better solution here. 这可能是一个更好的解决方案。
I hope it helps. 希望对您有所帮助。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.