3

I'm trying to set the focus to the first blank input or textarea field on a page. This works with inputs, but not with textareas.

$(':input:text[value=""]').first().focus() 

Can anyone help me?

4 Answers 4

3

You can try looking with something like

$("textarea:empty,input:text[value='']").first().focus(); 

Text areas don't have a value at all as they are called with

<textarea>Content</textarea> 

working example http://www.bootply.com/ikSuqoPMqs

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

2 Comments

It should work well for you now exactly how you want it to.
Great to hear that it worked for you. A nice simple solution. :) Please accept the answer and upvote. :)
3

You'll have to find all input and textarea on the page in the correct order. You can query using their tag names $('input, textarea'), but to maintain the correct order use a class on all of them (.inputClass in the example). Then filter the non empty ones, and .focus() the 1st:

//** search for the input class and filter the elements found **/ var emptyAreas = $('.inputClass').filter(function(index, element) { return $.trim($(element).val()) === ''; // element .val() is '' after trimming white spaces = true }); emptyAreas.first().focus(); // get the 1st element and focus it
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><input class="inputClass" value="text"></li> <li><textarea class="inputClass"></textarea></li> <li><input class="inputClass" value=" "></li> <li><textarea class="inputClass">text</textarea></li> <li><textarea class="inputClass"> </textarea></li> </ul>

Comments

0

My proposal is:

$(':text, textarea').on('blur', function(e) { var emptyField = $(':text, textarea').filter(function(index, element) { return element.value == ''; }); if (emptyField.length > 0) { emptyField.first().focus(); } });
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <form> First name:<br> <input type="text" name="firstname"><br> Last name:<br> <input type="text" name="lastname"> Comment:<br> <textarea name="comment" form="usrform"></textarea> </form>

Comments

0

Good point on the .inputClass. @Ori Drori

I've improved your answer a bit. Excluding hidden fields and adding the .inputClass dynamically.

// adding .inputClass to inputs to maintain the order in the filter below $('input, textarea').addClass('inputClass'); const emptyAreas = $('.inputClass').filter(function (index, element) { const hidden = $(element).is('hidden') || $(element).attr('type') === 'hidden'; // excluding hidden elements return !hidden && $.trim($(element).val()) === ''; // element .val() is '' after trimming white spaces }); emptyAreas.first().focus(); // get the 1st element and focus it 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.