finst33
finst33

Reputation: 141

jQuery resets textarea on any click, but is said to only do so when the textarea has a certain value

I'm currently experiencing a problem. I'm trying to reset my textarea, if it has the value Message...(which it has when you load the page). But as it is now, it resets no matter what value it has. Here's my jquery code:

if ($("#text").value = 'Message...') 
{
    $("#text").click(function () {
        $(this).val('');
    });
}

The HTML code is just a textarea inside a form.

Upvotes: 0

Views: 96

Answers (2)

fbynite
fbynite

Reputation: 2661

A few of your problems are that

if ($("#text").value = 'Message...') 
// should be replaced with the line below
if ($(this).val() == 'Message...')

Notice the use of val() instead of value and instead of the assignment operator, I used the equality operator (you could also the identity operator ===).

Also, the reason why your text is always being reset is because your event handler is resetting the text each time you click the #text element, so to achieve the expected behavior you need to wrap the logic inside the event handler.

$("#text").click(function () {
  if ($(this).val() == 'Message...')
    $(this).val('');
 });

If you wanted to achieve a "placeholder" effect you could use the following instead:

$("#text").focusin(function () {
  if ($(this).val() == 'Message...')
    $(this).val('');
}).focusout(function() {
  if ($(this).val() == '')
    $(this).val('Message...');
});

Upvotes: 1

adamb
adamb

Reputation: 4883

$("#text").value = 'Message...' will always be true because you're using the assignment operator. use === instead for comparison.

if ($("#text").val() === 'Message...') 
{
    $("#text").click(function () {
        $(this).val('');
    });
}

Upvotes: 1

Related Questions