Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Change button text on click

Tags:

jquery

After seeing Toggling button text in jquery this question, I tried to re create it in my situation but can't seem to have it work.

Here is a fiddle of what I've done: http://jsfiddle.net/V4u5X/

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore');
    if($this.hasClass('.SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

It seems to only ever run the if statement once. What am I missing?

like image 488
Scherf Avatar asked Oct 14 '13 17:10

Scherf


People also ask

How to Change text of a button in jQuery?

Answer: Use the jQuery prop() and html() Methods You can simply use the jQuery prop() method to change the text of the buttons built using the HTML <input> element, whereas to change the text of the buttons which are created using the <button> element you can use the html() method.

How to Change button title in jQuery?

To set the title property on an element, use: $('#yourElementId'). prop('title', 'your new title');

How do you change the name of a button?

To manually rename a new button:Click on the new button to select it (or Ctrl+Click, if a macro has been assigned to the button). Click in the Name Box, at the left of the Formula Bar. Type a new name, to replace the existing butto name. Press Enter, to complete the name change.


2 Answers

$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');         
    } else {
        $this.text('See Less');
    }
});

This should do it. You have to make sure you toggle the correct class and take out the "." from the hasClass

http://jsfiddle.net/V4u5X/2/

like image 177
Kierchon Avatar answered Sep 21 '22 12:09

Kierchon


try this, this javascript code to change text all time to click button.http://jsfiddle.net/V4u5X/2/

html code

<button class="SeeMore2">See More</button>

javascript

$('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
    });
like image 42
Abhishek Avatar answered Sep 20 '22 12:09

Abhishek