user3730179 user3730179 - 5 months ago 11
jQuery Question

select text and replace in for loop

I am having trouble solving this. I need to create a grid with square emojis. 11 squares across and 68 rows. I have created that. now my problem is targeting a square in a specific row and position in the row, and replacing it with a different emoji. the class .emoji-generator is a textarea element. i tried appending it and that seems to do the trick. but i need to replace the square with a different emoji and not add it to the line. there could only be 11 characters in each row. what is the best way of going about this?

var SQUARE_EMOJI = '\u25FB\uFE0F ';
var DROPLET_EMOJI = '\ud83d\udca7';

function reset() {
for (var i = 1; i<=68; i++) {
for(var y = 0; y <11; y++) {
$('.emoji-generator').append(SQUARE_EMOJI);
if (i == 6 && y == 5 ) {
$('.emoji-generator')[y].append(DROPLET_EMOJI);
}
}
$('.emoji-generator').append('\r\n');
}
};

Answer

textarea element content is not manipulated by the append method, which is destined for inserting nodes. Instead you should use the val method for setting its content. And to improve performance it is best to do that only once at the end of your function:

var SQUARE_EMOJI = '\u25FB\uFE0F ';
var DROPLET_EMOJI = '\ud83d\udca7';

function reset() {
    var content = '';
    for (var i = 1; i<=68; i++) {
        for(var y = 0; y <11; y++) {
            if (i == 6 && y == 5 ) {
                content += DROPLET_EMOJI;
            } else {
                content += SQUARE_EMOJI;
            }
        }
        content += '\n';
    }
    $('.emoji-generator').val(content);
};