Pregunta

En mi formulario, tengo un conjunto de cuadros de entrada donde un usuario puede ingresar un valor. Al cambiar uno de estos cuadros, el formulario se envía automáticamente.

Sin embargo, el problema ahora es que un usuario permanece en el último campo, toma el mouse y presiona el botón OK (de otra forma) sin salir primero del cuadro de texto. El evento de cambio no se activa y los valores antiguos e incorrectos se pasan a la página siguiente.

Quiero activar el evento onchange después de unos pocos milisegundos de teclado inactivo. Al igual que la mayoría de los complementos de autocompletar.
Creo que podría implementar un temporizador que comienza a cronometrar el momento en que ingresa un campo de entrada y se restablece cada vez que se maneja una pulsación de tecla y luego, cuando llega a cero, se activa el evento onchange.

No estoy dispuesto a reinventar la rueda y me preguntaba si esa función está disponible en algún lugar.
¿Sugerencias?

¿Fue útil?

Solución

Tuve un problema similar y creé un complemento jQuery actualmente en uso en una aplicación interna. Debería activar el evento de cambio después de que el usuario haya terminado de escribir.

Si no está utilizando jQuery, el código aún se puede adaptar a cualquier otra cosa.

jQuery.fn.handleKeyboardChange = function(nDelay)
{
    // Utility function to test if a keyboard event should be ignored
    function shouldIgnore(event) 
    { 
        var mapIgnoredKeys = {
             9:true, // Tab
            16:true, 17:true, 18:true, // Shift, Alt, Ctrl
            37:true, 38:true, 39:true, 40:true, // Arrows 
            91:true, 92:true, 93:true // Windows keys
        };
        return mapIgnoredKeys[event.which];
    }

    // Utility function to fire OUR change event if the value was actually changed
    function fireChange($element)
    {
        if( $element.val() != jQuery.data($element[0], "valueLast") )
        {
            jQuery.data($element[0], "valueLast", $element.val())
            $element.trigger("change");
        }
    }

    // The currently running timeout,
    // will be accessed with closures
    var timeout = 0;

    // Utility function to cancel a previously set timeout
    function clearPreviousTimeout()
    {
        if( timeout )
        { 
            clearTimeout(timeout);
        }
    }

    return this
    .keydown(function(event)
    {
        if( shouldIgnore(event) ) return;
        // User pressed a key, stop the timeout for now
        clearPreviousTimeout();
        return null; 
    })
    .keyup(function(event)
    {
        if( shouldIgnore(event) ) return;
        // Start a timeout to fire our event after some time of inactivity
        // Eventually cancel a previously running timeout
        clearPreviousTimeout();
        var $self = $(this);
        timeout = setTimeout(function(){ fireChange($self) }, nDelay);
    })
    .change(function()
    {
        // Fire a change
        // Use our function instead of just firing the event
        // Because we want to check if value really changed since
        // our previous event.
        // This is for when the browser fires the change event
        // though we already fired the event because of the timeout
        fireChange($(this));
    })
    ;
}

Uso:

$("#my_input").handleKeyboardChange(300).change(function()
{
    // value has changed!
});

Otros consejos

¿No funciona hacer un onBlur, entonces cuando el usuario pasa al siguiente campo o hace clic en otra cosa, el valor se guarda?

No sé si tal solución se consideraría "reinventar" cualquier cosa. Como dijiste, parece que no es más que un simple setTimeout una vez que se carga la página. Después de unos 3.000 milisegundos, ejecuta form.submit ().

Probablemente reiniciaría la cuenta regresiva con cada pulsación de tecla también, para darle al usuario suficiente tiempo para hacer su entrada.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top