Ben
Ben

Reputation: 85

firing all keydown/up events in contenteditable div

my problem... I can't seem to fire all the keydown events.

I am using an [enter] and [esc] keydown event to update/refresh or exit/refresh data in some html tables

there are static table cells and dynamic table cells, populated based on the users search-term input

dynamic tables come from a $.each loop but the div structures are exactly the same ( and div id's are unique ). in both cases the resulting table cell is...

<td class="edit"><div contenteditable="true" id="XYZ">[value]</div></td>

the keydown functions are exactly the same....

$(document).ready(function() {

    $("#divA").keydown(function (e) { 
    if (e.keyCode == 13) {
        e.preventDefault();
        // send data to server          
        // refresh stuff
    } 
    if (e.keyCode == 27) {
        // refresh stuff
    }       
    });

    $("#divB").keydown(function (e) { 
    if (e.keyCode == 13) {
        e.preventDefault();
        // send data to server
        // refresh stuff        
    } 
    if (e.keyCode == 27) {
        // refresh stuff
    }       
    });

the separate functions posting date to the server are the same. and the php to update the database is the same also. and both have the same mysql data structure double, yes null, zero default. divB exists with data in it and alert($("#divB").text()); shows the values that would be used in the ajax update.

but I guess none of that matters because I have narrowed the problem to here...

in divA, keydown stops the [enter] line-break and runs the code

in divB, keydown does not stop the [enter] line-break and none of the code runs

the only difference is divA is static and divB is generated in javascript. how can I get the divB keydown function to run ?

Upvotes: 1

Views: 2224

Answers (1)

Tomer
Tomer

Reputation: 17930

Since some of the divs are dynamic you can't use keydown to bind events to them. this method will only bind to existing divs when the page loads.

What you need is to use jquery.on() or jquery.live() (on is newer so if your jquery version support it, better to use it).

Upvotes: 3

Related Questions