Search code examples
javascriptjquerycontenteditableunique-id

How can I assign Id attribute to all the children of a contenteditable div on keyup?


I tried the following:

HTML:

<div contenteditable="true" id="editable"></div>

JS:

$('#editable').keyup(function() {
    addID();
});

function addID()
{
    $('#editable *').each(function() {

        var t = GenerateID();

        $(this).attr('id','id-' + t);

    });
}

function GenerateID() 
{
    var str = 'abcdefghijklmnopqrstuvwxyz0123456789';

    var alphabet = '', 
        genID = '';

    while(genID.length < 5)
    {
        alphabet = str.charAt(Math.floor(Math.random() * str.length)); 
        genID += alphabet;
    }

    return genID;
}

But on every keyup it keeps on changing the ID.

How can I just set the id once for all the elements while typing, and still keep it unique throughout the div ?

JSFiddle


Solution

  • LAST UPDATE: Now I checked the code in your fiddle and I'm sure it works. The checking for uniqueness can probably be made into a function, but i'll leave that to you:

    $('#editable').on( 'keyup', addID );
    
    
    var count = 0;  // this will absolutely ensure that ID will be unique
    
    function addID(){  
    
        var previousIDs = [];
    
        $('#editable *').each(function() {
    
            count++;
            var thisID = $(this).attr( 'id' );
    
            // let's check if we have duplicates:
            var index = 0, len = previousIDs.length, isDuplicate = false;
    
            for( index = 0; index < len; index++ ){
                if ( thisID === previousIDs[index] ) { 
                    isDuplicate = true; 
                    break;
                }
            }
    
    
            // now change the ID if needed:
            if (  isDuplicate    ||    ! thisID  ){
    
                var t = GenerateID();
                var newID = 'id-' + t + '-' + count;
    
                $(this).attr('id', newID);
                previousIDs.push( newID );
    
            }else{
                previousIDs.push( thisID );
            }
    
        });
    }
    

    Working Fiddle