1

Consider this HTML:

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

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();
});

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.

What am I missing?

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

2 Answers 2

7

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;
    }
});

Here's your fiddle: http://jsfiddle.net/TYjNE/2/

Sign up to request clarification or add additional context in comments.

1 Comment

probably you should add the name also to the filter
1

The below code will help you find if any first input field empty from a list of all input fields on the form.

 $(document).ready(function(){

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

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

I hope you wanted this. It helps you in finding the first empty field. Here is the fiddle check out. http://jsfiddle.net/TYjNE/4/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.