Yasitha
Yasitha

Reputation: 111

How to clear the content of the html input text field using Jquery

I am having a html text field which can hide.

When hiding I want clear the text field.

I used this and it doesn't work.

$('#id').val("");

And I tried $('#id').text(""); as well.

It removed the whole text field.

Upvotes: 5

Views: 19028

Answers (4)

magulla
magulla

Reputation: 509

Please try this:

 $('#id').attr("value","");

Upvotes: 2

kazinix
kazinix

Reputation: 30103

Assuming that TheTextField is the ID of your input field, this works fine.

$('#TheTextField').val("");
$('#TheTextField').hide();

Anyway, if you are using FireBug and you look at the input field while hidden, you will see that value attribute still has a value, which it really doesn't have, but when you show it again:

$('#TheTextField').val("");
$('#TheTextField').hide();
$('#TheTextField').show();

the input field as you will see it rendered in the browser as opposed to what you are seeing in the FireBug, it has no value anymore.

Upvotes: 1

John Green
John Green

Reputation: 13435

This is correct:

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

However, your part 2 is interesting.

$('#id').text("");

That shouldn't create the behavior you're describing. I expect that you're referencing the parent object, not the <input> directly.

Upvotes: 8

Jason Gennaro
Jason Gennaro

Reputation: 34855

What else is happening with your code... because this works for me...

<input id="id">
<input id="clear" type="button" value="Clear">

and

$('#clear').click(function(){
    $('#id').val('');    
});

Working example: http://jsfiddle.net/jasongennaro/xrxU8/

Upvotes: 2

Related Questions