Peter
Peter

Reputation: 11835

Set textfield value without losing the focus

how can I change the value of a textarea or textfield

// Clean button

 $('#textfield').val('');

without losing the focus?

I create at the moment an webApp and the smartphone (android) loosing the focus (and the keyboard disappears) when i click on the cleanButton ... i must click on/in in the textfield again to write further (not good usability :/ )

Any ideas?

BTW.: this $('#textfield').val('').focus(); does not work.

Upvotes: 1

Views: 1316

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30557

Have you tried preventing default? You need to stop the browser event which will cause the focus to be lost by calling preventDefault on the event parameter in your callback

$('[type="button"]').mousedown(function(event) {
    event.preventDefault(); 
    $('[type="text"]').val('');
});

Also, make sure you capture attach the callback to mousedown and not click because the focuse will change automatically when mousedown is successful.

fiddle

Prevent firing focus event when clicking on div

Upvotes: 3

Fanckush
Fanckush

Reputation: 143

yes it would not work because in jquery .focus() is an event (similar to .click() while in JS .focus() puts focus on the desired element.

i know how to do it with javascript, try this:

var clrBtn = $('#cleanButton'); //from jQuery to JavaScript
$('#cleanButton').val('');
clrBtn.focus(); // here the focus goes to clnBtn (JS function)

Upvotes: 0

Related Questions