0

I have a box , like this :

<div class="box">
</div>

And i want to do something with jquery that changes the text of that element for each time that the .box get clicked !

For example,

for first time , i click on the box, i want to have : <div class="box">Test1</div>

For second time , i click on that , i want this : <div class="box">Test2</div>

+...

I khow i can use this code for click event :

$('.box').click(function(){
 $(this).text();
});

But i want something to do , to have multiple values for each click !

EDit : I don't need a value + count ! i need new string each time

4 Answers 4

1

You can use that code:

var myTexts = ["text1", "text2", "text3"];

$('div.box').click(function (indexOfArray) {
    $(this).text(myTexts[indexOfArray]);
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but not worked for me.. can u add JSFIDDLE ?
1

try to store your click count in a variable.

   var i = 0;
   $('.box').click(function(){
     i++;
     $(this).text('Test'+i);
   });

Comments

1
var clix = 1;
$('div.box').click(function () {
    $(this).text('Test' + clix++);
})

jsFiddle example

4 Comments

thanks, i don't need test + count ! How can i have a new string with new click ?
What kind of new string?
first one can be test and for new click : message and for third time : Hello!
Then you need to specify what these news strings are. Your question isn't clear. Like this jsfiddle.net/j08691/fujaN?
1

This is one way to do it. See this fiddle

$('.box').click(function(){
    var $this = $(this),
        count = $this.data("count") || 0;

    count += 1;
    $this.text("Test" + count.toString());

    $this.data("count", count);
});

4 Comments

thanks, i don't need test + count ! How can i have a new string with new click ?
I'm not sure what you're getting at. Would you mind specifying? Your original post said to put "Test1", "Test2", and so on.
No, the secound one can be Messaeg , the third one can be Hello! and so on . there is no increasing in number, just new strings
You will need to store those guys in an array and then reference them in the counter. You can update your post to indicate that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.