Eileen
Eileen

Reputation: 6660

jquery: How to empty a form field, then bring focus/cursor to it?

I have a form that I'm submitting with AJAX. A user fills out the field (called "barcode") and hits return, and the form submits.

After the form submits, they are shown a success or failure message. I want to:

  1. Fade out the message
  2. Empty the 'barcode' field
  3. Bring the cursor back to the field, ready for the next person.

So far I have got step 1 handled:

setTimeout(function(){ $('span.login-fail').parent().fadeOut('normal'); }, 1000); 
setTimeout(function(){ $('span.login-welcome').parent().fadeOut('normal'); }, 1000); 

But I do not know how to do 2 or 3. Thanks for any help!

Upvotes: 0

Views: 3416

Answers (3)

amitkaz
amitkaz

Reputation: 2712

var barcode = $('#barcode');
barcode.val('');
barcode.focus();

Upvotes: 0

Artem Barger
Artem Barger

Reputation: 41232

You can do:

$( "#form_id").find( "input").val( "").end( ).find( "input:first").focus();

this will clean all inputs in the form and move focus to the first one in the list.

Upvotes: 0

aolde
aolde

Reputation: 2305

  • To clear a field just use $("#fieldID").val("") which will set the value to nothing.

  • Focus is done just by using the focus method $("#fieldID").focus()

Upvotes: 2

Related Questions