Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

How to empty a textbox, textarea in jquery

var $contact_title = $('#contact_title').val();
var $contact_summary = $('#bbcode').val();

I retreive a text area and text field then I do this:

$contact_title.val('');
$contact_summary.val('');

Nnone of them get emptied

HTML:

<form action="" method="get">
    <table border="0">
        <tr>
            <td valign="top">Title:</td>
            <td>
                <input name="title" type="text" style="width:710px" id="contact_title" />
            </td>
        </tr>
        <tr>
            <td valign="top">Message:</td>
            <td>
                <textarea name="request" cols="30" rows="20" id="bbcode"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="right" >
                <input name="send" type="button" onClick="clicked()" value="Send" />
            </td>
        </tr>
    </table>
</form>

Upvotes: 0

Views: 194

Answers (5)

St&#233;phane Bebrone
St&#233;phane Bebrone

Reputation: 2763

You should store the element in your variable and not the value.

So, your code should be:

var $contact_summary = $('#bbcode');
$contact_summary.val('');

Btw, it's a good practice to use unobtrusive javascript and bind your click event outside of your html markup:

$('button').click(function() { //clear inputs });

Upvotes: 3

Nikolay Fominyh
Nikolay Fominyh

Reputation: 9256

In js fiddle easier to write/read javascript code. Here is an answer. http://jsfiddle.net/7RFYx/

jQuery(document).ready(function () { 
    var $contact_title = $('#contact_title');
    var $contact_summary = $('#bbcode');
    var $contact_summary_val = $contact_summary.val();
    var $contact_title_val = $contact_title.val();
    $contact_title.val('');
    $contact_summary.val('');
});

Upvotes: 1

Shades88
Shades88

Reputation: 8360

you have to use the same syntax that you used while getting the values from those filed. try:

$('#contact_title').val('');
$('#bbcode').val('');

Upvotes: 1

nillls
nillls

Reputation: 623

Your variable ($contact_title) contains the text, not the actual DOM-element, from what I can tell. If you change it to

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

You'll be fine.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337714

Your problem is because you are setting your variables to be the string values of the elements, rather than the jQuery objects containing the elements.

Try this:

var $contact_title = $('#contact_title');
var $contact_summary = $('#bbcode');
$contact_title.val('');
$contact_summary.val('');

Or alternatively;

$('#contact_title').val('');
$('#bbcode').val('');

Upvotes: 3

Related Questions