Sven van den Boogaart
Sven van den Boogaart

Reputation: 12341

Change text of child

I'm trying to make a add to favorite system. I have a function which alerts the proper id I want to add.

I use:

 <script type="text/javascript">
 function addfavo(state_name)
 {
    alert(state_name);
 } 
 </script>

And in my html I have a loop (with php) which shows all the images with the add to favorite links which looks like.

<div style="margin-top:40px;">
    <a onclick="addfavo('<?php echo $imgid ?>')"><b>Add to favourits</b></a>
</div>

So what happens is I have a lot of links to the same function with different parameters, but I only want the link that I click to change the text (to something like added to favorites)

Can some one help me in the right direction?

I have tried adding:

 $(this).innerHTML("test");

but it didn't work.

Upvotes: 0

Views: 49

Answers (1)

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

You might want to use the html method:

$(this).html('test');

While html is a jQuery method, innerHTML is a property of a DOM element. If you were using pure JavaScript, you'd probably use:

this.innerHTML = 'test';

However, as you are using the onclick attribute on your HTML tag, this will not point to your current DOM element inside your function scope. In your case, I'd add a class to your elements, like add_favorite and add your text to another attribute:

<div style="margin-top:40px;">
    <a href="#" class="add-favorite" data-text="<?php echo $imgid ?>"><b>Add to favourits</b></a>
</div>

And then apply a jQuery event to it:

<script type="text/javascript">
    $(function() {
        $('.add-favorite').click(function(e) {
            var text = $(this).data('text'); // store the text in a variable
            $(this).html(text); // replace your element's html with your text
            e.preventDefault();
        });
    });
</script>

Fiddle: http://jsfiddle.net/MH6vY/

Upvotes: 1

Related Questions