最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger onClick event when Enter keypress in a Twitter Bootstrap Modal - Stack Overflow

programmeradmin1浏览0评论

I've a few modals build on top of Twitter Bootstrap Modal, each have at least one submit button which is the default action I need to trigger in most cases since the second button is for go back (dismiss the modal), how, on a modal, when I hit enter I can trigger whatever action that submit has? For example right now, as they are button I have something like:

$("#btn").on("click", function(e){
    e.preventDefault(); // wait... not send form yet, will be a Ajax call
});

Any help? Example code?

For reference, this is the modal content (I using with Twig as part of a Symfony2 project so don't worry about {{ }}):

<div class="modal fade " id="addNorma" tabindex="-1" role="dialog" aria-labelledby="addNorma" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">{{ 'boton.cerrar'|trans({}, 'AppBundle') }}</span></button>
                <h4 class="modal-title" id="myModalLabel">{{ 'modal.normas.titulo'|trans({}, 'AppBundle') }}</h4>
            </div>
            <div class="modal-body">
                <form id="buscadorNorma" method="POST">
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-5 col-lg-5 col-sm-5 col-xs-5">
                            <label for="codigo_norma">{{ 'modal.normas.codigo'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="codigo_norma" name="codigo_norma" placeholder="{{ 'modal.normas.codigoPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                        <div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 col-md-offset-2">
                            <label for="ano_publicacion">{{ 'modal.normas.anno'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="ano_publicacion" name="ano_publicacion" placeholder="{{ 'modal.normas.annoPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                    </div>
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="nombre_norma">{{ 'modal.normas.term'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="nombre_norma" name="nombre_norma" placeholder="{{ 'modal.normas.termPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                    </div>
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="procedencia_producto">{{ 'modal.normasite'|trans({}, 'AppBundle') }}</label>
                            <div class="form-group">
                                <div>
                                    <select name="ite_tecnico" id="ite_tecnico" class="form-control toSelect2">
                                        <option value="" selected="selected">{{ 'seleccioneOpcion'|trans({}, 'AppBundle') }}</option>
                                        {% for key, item in iteTecnico %}
                                            <option value="{{ key }}">{{ item.nombre }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="spacer5"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <button type="button" class="btn btn-default pull-right" disabled="disabled" id="btnBuscarNorma"><i class="fa fa-binoculars"></i> {{ 'boton.buscar'|trans({}, 'AppBundle') }}</button>
                        </div>
                    </div>
                </form>
                <div class="spacer10"></div>
                <table  class="table table-hover table-condensed" id="resultadoNorma" style="display: none">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="toggleCheckboxNorma" name="toggleCheckboxNorma" /></th>
                            <th>{{ 'columnas.normas.no'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.norma'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.anno'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normasite'|trans({}, 'AppBundle') }}</th>
                        </tr>
                    </thead>
                    <tbody id="resultadoNormaBody"></tbody>
                </table>
                <div class="alert alert-danger" role="alert" style="display: none;" id="sinResultadosBuscarNormas">
                    {{ 'mensajes.msgNoEncontrado'|trans({}, 'AppBundle') }}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">{{ 'boton.regresar'|trans({}, 'AppBundle') }}</button>
                <button type="submit" class="btn btn-primary" id="btnAplicarNorma" disabled="disabled"><i class="fa fa-save"></i> {{ 'boton.aplicar'|trans({}, 'AppBundle') }}</button>
            </div>
        </div>
    </div>
</div>

And that's the code I trigger when I click on #btnBuscarNorma:

$('button#btnBuscarNorma').on('click', function (ev) {
    ev.preventDefault();
    $.post(Routing.generate('filtrarNormas'), $('#buscadorNorma').serialize(), 'json')
        .done(function (data, textStatus, jqXHR) {
            $('#resultadoNorma').toggle(!!data.entities.length);
            $("#sinResultadosBuscarNormas").toggle(!data.entities.length);

            if (data.entities.length > 0) {
                var $html = '';
                data.entities.forEach(function (value, index, array) {
                    $html += '<tr>';
                    $html += '<td><input type="checkbox" id="' + value.id + '" value="' + value.id + '"></td>';
                    $html += '<td>' + value.codigo + '</td>';
                    $html += '<td>' + value.norma + '</td>';
                    $html += '<td>' + value.anno + '</td>';
                    $html += '<td>' + valueiteTecnico + '</td>';
                    $html += '</tr>';
                });

                $("table tbody#resultadoNormaBody").html($html);
                marcarTodosCheck('#toggleCheckboxNorma', '#resultadoNormaBody');
            }
        });
});

The idea is Enter key will trigger #btnBuscarNorma click event and not #btnAplicarNorma click event.

I've a few modals build on top of Twitter Bootstrap Modal, each have at least one submit button which is the default action I need to trigger in most cases since the second button is for go back (dismiss the modal), how, on a modal, when I hit enter I can trigger whatever action that submit has? For example right now, as they are button I have something like:

$("#btn").on("click", function(e){
    e.preventDefault(); // wait... not send form yet, will be a Ajax call
});

Any help? Example code?

For reference, this is the modal content (I using with Twig as part of a Symfony2 project so don't worry about {{ }}):

<div class="modal fade " id="addNorma" tabindex="-1" role="dialog" aria-labelledby="addNorma" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">{{ 'boton.cerrar'|trans({}, 'AppBundle') }}</span></button>
                <h4 class="modal-title" id="myModalLabel">{{ 'modal.normas.titulo'|trans({}, 'AppBundle') }}</h4>
            </div>
            <div class="modal-body">
                <form id="buscadorNorma" method="POST">
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-5 col-lg-5 col-sm-5 col-xs-5">
                            <label for="codigo_norma">{{ 'modal.normas.codigo'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="codigo_norma" name="codigo_norma" placeholder="{{ 'modal.normas.codigoPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                        <div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 col-md-offset-2">
                            <label for="ano_publicacion">{{ 'modal.normas.anno'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="ano_publicacion" name="ano_publicacion" placeholder="{{ 'modal.normas.annoPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                    </div>
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="nombre_norma">{{ 'modal.normas.term'|trans({}, 'AppBundle') }}</label>
                            <input type="text" class="form-control" id="nombre_norma" name="nombre_norma" placeholder="{{ 'modal.normas.termPlaceholder'|trans({}, 'AppBundle') }}">
                        </div>
                    </div>
                    <div class="spacer10"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="procedencia_producto">{{ 'modal.normas.ite'|trans({}, 'AppBundle') }}</label>
                            <div class="form-group">
                                <div>
                                    <select name="ite_tecnico" id="ite_tecnico" class="form-control toSelect2">
                                        <option value="" selected="selected">{{ 'seleccioneOpcion'|trans({}, 'AppBundle') }}</option>
                                        {% for key, item in iteTecnico %}
                                            <option value="{{ key }}">{{ item.nombre }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="spacer5"></div>
                    <div class="row">
                        <div class="col-md-12">
                            <button type="button" class="btn btn-default pull-right" disabled="disabled" id="btnBuscarNorma"><i class="fa fa-binoculars"></i> {{ 'boton.buscar'|trans({}, 'AppBundle') }}</button>
                        </div>
                    </div>
                </form>
                <div class="spacer10"></div>
                <table  class="table table-hover table-condensed" id="resultadoNorma" style="display: none">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="toggleCheckboxNorma" name="toggleCheckboxNorma" /></th>
                            <th>{{ 'columnas.normas.no'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.norma'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.anno'|trans({}, 'AppBundle') }}</th>
                            <th>{{ 'columnas.normas.ite'|trans({}, 'AppBundle') }}</th>
                        </tr>
                    </thead>
                    <tbody id="resultadoNormaBody"></tbody>
                </table>
                <div class="alert alert-danger" role="alert" style="display: none;" id="sinResultadosBuscarNormas">
                    {{ 'mensajes.msgNoEncontrado'|trans({}, 'AppBundle') }}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">{{ 'boton.regresar'|trans({}, 'AppBundle') }}</button>
                <button type="submit" class="btn btn-primary" id="btnAplicarNorma" disabled="disabled"><i class="fa fa-save"></i> {{ 'boton.aplicar'|trans({}, 'AppBundle') }}</button>
            </div>
        </div>
    </div>
</div>

And that's the code I trigger when I click on #btnBuscarNorma:

$('button#btnBuscarNorma').on('click', function (ev) {
    ev.preventDefault();
    $.post(Routing.generate('filtrarNormas'), $('#buscadorNorma').serialize(), 'json')
        .done(function (data, textStatus, jqXHR) {
            $('#resultadoNorma').toggle(!!data.entities.length);
            $("#sinResultadosBuscarNormas").toggle(!data.entities.length);

            if (data.entities.length > 0) {
                var $html = '';
                data.entities.forEach(function (value, index, array) {
                    $html += '<tr>';
                    $html += '<td><input type="checkbox" id="' + value.id + '" value="' + value.id + '"></td>';
                    $html += '<td>' + value.codigo + '</td>';
                    $html += '<td>' + value.norma + '</td>';
                    $html += '<td>' + value.anno + '</td>';
                    $html += '<td>' + value.iteTecnico + '</td>';
                    $html += '</tr>';
                });

                $("table tbody#resultadoNormaBody").html($html);
                marcarTodosCheck('#toggleCheckboxNorma', '#resultadoNormaBody');
            }
        });
});

The idea is Enter key will trigger #btnBuscarNorma click event and not #btnAplicarNorma click event.

Share Improve this question edited Nov 26, 2014 at 14:44 ReynierPM asked Nov 26, 2014 at 13:56 ReynierPMReynierPM 18.7k55 gold badges204 silver badges387 bronze badges 2
  • For reference stackoverflow./questions/24958558/… stackoverflow./questions/19297520/… – Swapnil Motewar Commented Nov 26, 2014 at 14:12
  • Possible duplicate of detect key press on modal dialog not working – Vic Seedoubleyew Commented Jul 18, 2019 at 14:22
Add a ment  | 

3 Answers 3

Reset to default 6

Bind this event when you open a modal.

//to prevent multiple binding
$(document).unbind("keyup").keyup(function(e){ 
    var code = e.which; // remended to use e.which, it's normalized across browsers
    if(code==13)
    {
        $("#btn").click();
    }
});

You can listen for a form submit and prevent it.

$('#myform').on('submit', function (e) {
  e.preventDefault();
});

This way you can make sure the form is never submitted. You can also start the Ajax call when the submit function is called.

A normal button <button> also doesn't submit the form.

When modal is opened in class is active on it. So you can get in JQuery:

$("#addNorma.in").on("keydown",function(e){
    if(e.which == 13){
        //Do something.
    }
});
发布评论

评论列表(0)

  1. 暂无评论