nathan
nathan

Reputation: 11

ajax/jquery/javascript

I have a function that toggles a button: now I would like to display the text next to the button in 2 different colors based on the response.

This is my code:

function toggleMustHave(){
    $.ajax({
        type: "POST",
        dataType: "json",
        url: '{$ajaxUrl}&act=toggleMustHave',
        data: 'storeId={$storeId}',
        success: function(data){
            $('#mustHave').html('<span id="mustHave" >'+data['mustHaveButtonText']+ '&nbsp;&nbsp;-->&nbsp;&nbsp;'+'</span>');
            $('#mustHaveButton').text(data['mustHaveButtonText']);
        }
    });
}

Upvotes: 0

Views: 91

Answers (2)

Marco Pace
Marco Pace

Reputation: 3870

You can do it with two step:

1) The first is to add to you css two new classes, one for every different response you will receive

2) The second is to modify you "success" function to append the next you need after the button:

function toggleMustHave(){
    $.ajax({
        type: "POST",
        dataType: "json",
        url: '{$ajaxUrl}&act=toggleMustHave',
        data: 'storeId={$storeId}',
        success: function(data) {
            $('#mustHave').html('<span id="mustHave" >'+data['mustHaveButtonText']+ '&nbsp;&nbsp;-->&nbsp;&nbsp;'+'</span>');
            $('#mustHaveButton').text(data['mustHaveButtonText']);

            var yourClass // write here your condition

            $('<p class="'+ yourCLass +'">Your text response</p>').insertAfter('#mustHaveButton');
        }
    });
}

Remember to modify you "yourClass" value, depending on your result (you can use simply an if clause)

Upvotes: 1

socha23
socha23

Reputation: 10239

Change CSS class of your #mustHaveText in your success handler.

success: function(data){
    $('#mustHave').html('<span id="mustHaveText" >'+data['mustHaveButtonText']+      '&nbsp;&nbsp;-->&nbsp;&nbsp;'+'</span>');
    $('#mustHaveButton').text(data['mustHaveButtonText']);

    var text = $('#mustHaveText');

    text.removeClass('color1');
    text.removeClass('color2');

    if ( conditionOnReturnedDataHere()) {
        text.addClass('color1');
    } else {
        text.addClass('color2');
    }
}

Upvotes: 1

Related Questions