jQuery:选择第一个空文本输入 [英] jQuery: selecting first empty text input

查看:187
本文介绍了jQuery:选择第一个空文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此HTML:

<input type="text" name="userinput[]" />
<input type="text" name="userinput[]" />
<a href="javascript:void(0);">More</a>

这里的意图是让用户在表单字段中输入值,如果他们想要更多字段,点击链接将执行此jQuery:

The intent here is for users to input values into the form fields and, should they want more fields, clicking the link will execute this jQuery:

$('a').click( function(e) {
    e.preventDefault();
    $(this).before('<input type="text" name="team_names[]" />');

    //refocus on the first empty input
    $('input[value=""]:first').focus();
});

因此,用户A填写两个表单字段,点击更多链接,添加了输入字段,浏览器集中在第三个整体字段(因为它是第一个空字段)。不幸的是,代码选择第一个整体字段。我可以使它专注于最后一个输入字段...没有问题...但如果用户多次点击更多,然后再填充额外的字段,我仍然想关注第一个空字段。

So "User A" fills in the two form fields, clicks the "More" link, two more input fields are added and the browser focuses on the third overall field (due to it being the first empty field). Unfortunately, the code selects the first overall field. I can make it focus on the last input field... no problem... but if the user clicks "More" multiple times before filling in additional fields, I still want to focus on the first empty field.

我缺少什么?

http://jsfiddle.net/TYjNE/1/

推荐答案

属性选择器,但是当输入的值更改时,属性不更新。

You're using an attribute selector, but the value attribute isn't updated when the value of the input changes.

而是循环遍历它们,只关注实际上具有空值的那个:

Instead, loop through them, and only focus on the one that actually has an empty value:

$('input[name="userinput[]"]').each(function() {
    if ( this.value === '' ) {
        this.focus();
        return false;
    }
});

这是你的小提琴: http://jsfiddle.net/TYjNE/2/

这篇关于jQuery:选择第一个空文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆