Question

I've been learning more and more about jQuery but here I've become stuck.

I have a code to change the color of a div when a checkbox is cliked, that works fine.

After this I want to be able to change the contents of a textarea on focus, I tried this:

    //textarea
    $("textarea").focus(function(){
        if ($(this).contains('Skriv valg av headset her')){
         $(this).replaceWith('');
    });  

But there is no effect. Do I have some syntax errors or am I taking the wrong approach?

jsFiddle example here.

Was it helpful?

Solution

There's the $.contains function and the :contains selector, but no jQuery.fn.contains. You're looking for val here I believe:

$('textarea').focus(function(){
    var t = $(this);

    if(t.val().indexOf('Skriv valg av headset her') !== -1) {
        t.val('');
    }
});

replaceWith is also wrong here - if that were to work (and it shouldn't I believe because it takes either a DOM element or a HTML text) it would remove the textarea element (which is better done with remove anyway)

OTHER TIPS

Try this:

//textarea
$("textarea").focus(function(){
    var $this = $(this); // Always cache your selector

    if ($this.contains('Skriv valg av headset her'))
    {
        $this.val('');
    }
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top