0

I got a JS method that changes depending on the state of the button, defined by the indexOf("..some text..")

$('#add1').click(function(){
    if($(this).text().indexOf("Add Me!")) {
        $.ajax({
            type: 'post',
            url: '{{ URL('schedulizer/add') }}',
            data: {
                "class": ["Saab", "Volvo", "BMW"],
                _token: "{{ csrf_token() }}"
            },
            dataType: 'json'
        }).done(function(data){
            ... do stuff ...
        });
        $(this).removeClass('btn-material-yellow-600');
        $(this).addClass('btn-danger');
        $(this).text('Remove Me!');
        return false;
    } else if($(this).text().indexOf("Remove Me!")){
        $.ajax({
            type: 'post',
            url: '{{ URL('schedulizer/remove') }}',
            data: {
                "class": ["Saab", "Volvo", "BMW"],
                _token: "{{ csrf_token() }}"
            },
            dataType: 'json'
        }).done(function(data){
            ... do stuff ...
        });
        $(this).removeClass('btn-danger');
        $(this).addClass('btn-material-yellow-600');
        $(this).text('Add Me!');
        return false;
    }
});

What works:

When I click the initial "Add Me!", it would change to "Remove Me!". However, when the state of the button is in "Remove Me!", it seems the conditional is not satisfied, and the state stays in "Remove Me" no matter how many times I press the button.

Apologies for the messy and redundant code.. I'm very very new to JS, so everything is a muck fest.

2
  • Try to remove/comment out 'done' callbacks and check if somethnig will change, or even remove ajax functions for now Commented Aug 5, 2015 at 18:43
  • What does your button look like? Commented Aug 5, 2015 at 18:45

3 Answers 3

3

The indexOf return the position of the string it finds, and the position of your string is confusing the conditional if/else and it is always landing on the else if condition. Use == operator as follows :

$('#add1').click(function(){
  

    if($(this).text().trim() == "Add Me!") {
        
        $(this).text('Remove Me!');
        return false;
      
    } else if($(this).text().trim() == "Remove Me!"){
       
        $(this).text('Add Me!');
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="add1">Add Me!</button>

Sign up to request clarification or add additional context in comments.

5 Comments

== and indexOf() won't match if there is any other text
The reason I used indexOf is because for some reason, the text returned from $(this).text() contains numerous white space before/after the Add Me!, so I decided to use indexOf instead.
use trim($(this).text()) == 'Add Me!' this shall remove white space before/after the Add Me!
Why == instead of the stronger ===?
Well here you are safe as of type matching since javascript is string based and the button text is a string
2

indexOf() needs a comparison when used in conditional since 0 is valid index but will be falsy in the conditional.

Use greater than -1 for truthy test since it will be -1 if index doesn't exist

if($(this).text().indexOf("Add Me!") >-1)..

14 Comments

While this works, you should use the == operator since that is what it's designed for (comparing two values). Searching a string for a substring should only be used when the string could potentially be larger than the substring. Using the correct code will help you if you ever revisit this code in the future so you don't spend any time trying to figure out why you were searching "Add me" for a substring value of "Add me"
The reason I used indexOf is because for some reason, the text returned from $(this).text() contains numerous white space before/after the Add Me!, so I decided to use indexOf instead.
Did you read his code? He changes the text of the button to "Add Me" or "Remove Me".
@theGreenCabbage can use trim() or $.trim() to remove whitespace on ends
@Stan no...actually i didn't see that. regardless this answer stands as it helps OP understand where it went wrong
|
0

html

<button id="add1">Add Me!</button>

Javascript/Jquery

$add1Btn = $('#add1');

$add1Btn.click(function() {
    var btnText = $add1Btn.html();
    console.log(btnText);

    if (btnText === 'Add Me!') {
            $add1Btn.html('Remove Me!');
    } else if (btnText === 'Remove Me!') {
            $add1Btn.html('Add Me!');
    }
});

http://jsfiddle.net/zymcm6jv/

Your AJAX calls may be causing an issue if things don't seem to be working properly. Also, I think you would want to be putting the change of text in the success call back for the AJAX call, that way the text will change once the response has been received.

Comments

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.