dvglsk
dvglsk

Reputation: 37

jQuery text change with conditional

It's pretty basic stuff but I can't figure out the solution, from the few resources I found. What am I doing wrong?

$('#jquery-toggle').click(function () {

    var buttontext = $('#jquery-toggle').text();

    if ($(buttontext = 'Toggled')) {
        ($('#jquery-toggle').text('Not Toggled'));
    } else {
        ($('#jquery-toggle').text('Toggled'));
    }
});

Thanks in advance.

Upvotes: 1

Views: 2382

Answers (3)

empiric
empiric

Reputation: 7878

The main issue is this line:

if ($(buttontext = 'Toggled')) {
  • You mustn't wrap your variable into a jquery object
  • = is an assignment, == or === is a comparison

Additionally you have superfluous parenthesis around the .text() function inside the condition.

$('#jquery-toggle') can be changed to $(this), this will point to the element the event-handler was invoked on.

The code then would be:

 $('#jquery-toggle').click(function () {

        var buttontext = $(this).text();

        if (buttontext === 'Toggled') {
            $(this).text('Not Toggled');
        } else {
            $(this).text('Toggled');
        }
    });

Upvotes: 1

lotfio
lotfio

Reputation: 1936

Your main problem is with the single equal sign, which is an assignment operator (assigns a values to a variable), not a comparison operator (checks whether the two elements are equal), which is what you are after.

The following should work:

$('#jquery-toggle').click(function () {

    var buttontext = $(this).text();

    if (buttontext == 'Toggled') {

        $(this).text('Not Toggled');

    } else {
        $(this).text('Toggled');
    }
});

Note also the use of this, which saves you the computation of searching the document by id.

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Your if() shouldn't have $() in it and needs to use a comparison operator,not =

Can shorten this by using text(function)

$('#jquery-toggle').click(function () {
    // "this" is the element
    $(this).text(function(_, existingText){
       return existingText === 'Toggled' ? 'Not Toggled' : 'Toggled';
    });    
});

Upvotes: 1

Related Questions