0

I'm mainly a backend dev and I'm struggling with some basic jQuery functionality. I have a list of cars and a button to add them to "my collection", such as:

    <button type="button" value="19145" rel="add_to_collection" class="btn btn-primary btn-sm"><i class="bi bi-plus-circle"></i> Add to collection</button>
<!-- more html --->
    <button type="button" value="19146" rel="add_to_collection" class="btn btn-primary btn-sm"><i class="bi bi-plus-circle"></i> Add to collection</button>

and I have an endpoint /api/me/cars where I send a POST requet with the item id and stores it in the user collection. That part already works :-)

Now what I want to do is change the class of the button from btn-primary to btn-success and also change the text of the button from "Add to your collection" to "In your collection".

Here's the jQuery code I have

$("button[rel='add_to_collection']").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/api/me/cars",
        data: {
            item: $(this).val()
        },
        success: function(result) {
            $(this).removeClass("btn-primary").addClass("btn-success");
            $(this).button( "option", "label", "new text" );
        },
        error: function( jqXhr, textStatus, errorThrown ){

        }
    });
});

Also, how can I get the content of the response if there's an error?

1 Answer 1

0

This should work :

$(this).removeClass("btn-primary");
$(this).addClass("btn-success");
$(this).html('your new text here');

To get the content of the response I'm pretty sure you can use the parameters of the success/error function.

hope this helps

Not the answer you're looking for? Browse other questions tagged or ask your own question.