2

How can I combine a text string with a variable for use as an array index?

For example, on this line from the code below:

$('.flip[id="item-3"]').fadeOut( 1500); 

how do I do something like: $('.flip[id="item-" + id]').fadeOut( 1500);

To make this div fade away: < div id="item-3" class="flip">?

$( ".delete" ).click(function() {
    var $this = $(this), id = $this.data('id');

    $.ajax({
        method: "post",
        url: "charts_manage.php",
        data: { id: id, do: 'delete' },
        success: function( data ) {

            $('.flip[id="item-3"]').fadeOut( 1500);

        }
    });
});

2 Answers 2

3

Insert variable in a middle like this:

$('.flip[id="item-' + id + '"]').fadeOut(1500);

Also it may be more comprehensive to use dedicated id selector:

$('#item-' + id).fadeOut(1500);
Sign up to request clarification or add additional context in comments.

2 Comments

Beauty! Thank you very much sir. I was forgetting the last part... + '" [smacks forehead with hand]
You are welcome! Anyway, use the second version $('#item-' + id) it's also fastest DOM selector.
0

Javascript allows you to concatenate strings with ints by simply adding them. You can create the string by concatenating the first part of the string, the id int, and the end of the string:

'.flip[id="item-' + id + '"]'

if id=3, this gives you ".flip[id="item-3"]".

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.