【问题标题】:How to connect button to input without form? I want the user to be able to use the enter key如何在没有表单的情况下将按钮连接到输入?我希望用户能够使用回车键
【发布时间】:2014-01-17 22:56:49
【问题描述】:

所以我不应该在这个输入字段上使用表单标签(导致每个后端人员的错误)

选择/活动激活提交时,我将如何允许用户使用Enter密钥?

用户可以手动点击添加组提交按钮,也可以tab点击,但不能直接进入点击:(

表格

<input type="text"
       id="group-code" value="Type your Group Code Here" name="Type your Group Code Here"
       onblur="if (this.value == '') {this.value = 'Type your Group Code Here';}"
       onfocus="if (this.value == 'Type your Group Code Here') {this.value = '';}"
       autocomplete="off"/>

<button class="btn" id="btn_join_group">add group</button>
<!--<input type="submit" id="btn_join_group" form="group-code" value="add group"/>-->

jQuery

$('#btn_join_group').unbind('click').bind("click", function(event) {

    var newGroup = $('#group-code').val();

    // Send Group code to server
    WHOAT.networking.getToServerWithAjax('/groups/join', newGroup, function (response) {
        var res = JSON.parse(response);

        if (res.result === 'success') {
            notification.setStatusAndFadeStatus(response);

        } else if (res.result === 'error') {
            notification.setStatusAndFadeStatus(response);
        }
    });
});

【问题讨论】:

    标签: javascript jquery forms input


    【解决方案1】:

    您可以像这样向输入添加侦听器:

    $('#group-code').keypress( function (e) {
        if (e.keyCode === 13) 
            sendAjax();
    });
    

    然后将您的 AJAX 块包装在一个名为 sendAjax 的函数中。这段代码未经测试,但想法应该是有效的。

    【讨论】:

    • 谢谢!这确实有效,我最终还是让表单工作了,只需要在上面返回 false
    • 我很高兴能帮上忙,@LeonGaban!
    【解决方案2】:

    你可以使用keypress事件

    $('#group-code').on('keypress', function (e) {
        var keyCode = e.which;
        if (keyCode == 13) {
            //Trigger click event
            $('#btn_join_group').trigger('click');
        }
    });
    

    【讨论】:

      【解决方案3】:

      在输入中添加keypress事件,如果为真触发按钮功能,则检查是否按下了回车键。

      $('input').on('keypress',function(event){
       if(event.keyCode == [the enter key code])
         //trigger the button click
      })  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-13
        相关资源
        最近更新 更多