如何在表单自动填充上触发我的Javascript表单处理程序?

时间:2011-09-05 00:00:47

标签: jquery events

我已经构建了一个类似于Twitter登录的表单,即。有一个<span>为每个<input>持有一个标签......然后在按键上,标签将它的font-size设置为0.这是一个很酷的效果。

我注意到的问题是,如果你使用表单自动填充,只有正确触发初始按键事件的表单会激活它的标签 - 其他标签没有正确地设置动画,因此重叠输入值。

我的问题是......如何弥补这一点?当表单自动填充输入输入值时会触发什么事件,更具体地说,我将如何在jQuery中使用它们?

。 。

以下示例表单:

<div class="name">
    <input class="name" name="name" type='text' value="<?php echo $name; ?>">
    <span>Full Name</span>
</div>

。 。

以下示例jQuery:

$(function(){
    // On document ready, check form fields
    $(':input').each(function() {
        if($(this).val() === "") {
            $(this).next('span').animate({fontSize:16},'fast');
        }
    });

    // On form focus, adjust colors
    $(':input').focus(function() {
        $(this).addClass('focus');
        $(this).next('span').addClass('focus');
    });

    // On keypress, remove label
    $(':input').keypress(function() {
        $(this).next('span').animate({fontSize:0},'fast',function(){
            $(this).hide();
        });
    });

    // On form blur, restore colors and label
    $(':input').blur(function() {
        $(this).removeClass('focus');
        $(this).next('span').removeClass('focus');
        if($(this).val() == '') {
            $(this).next('span').show().animate({fontSize:16},'fast');
        }
    });

    // Pass span 'click' event to input
    $('form span').click(function() {
        $(this).prev('input').trigger('focus');
    });
});

3 个答案:

答案 0 :(得分:2)

与此问题类似:How to bind to browser change of input field? (jQuery)

从本质上讲,浏览器在处理自动填充程序时似乎无法识别onchange事件。

我在那里看到的最好的解决方案(我知道它并不理想)是通过间隔一遍又一遍地检查字段的值。你会在上面链接的“类似”问题中找到一些基本思想的代码。

答案 1 :(得分:1)

考虑使用https://github.com/tbosch/autofill-event库,它为您处理所有奇怪的浏览器案例。

答案 2 :(得分:0)

您是否尝试过更改事件? http://api.jquery.com/change/