1

I use following code to dynamically add rows to my ASP.NET table. I create a span, then fill it with an html textbox code to create some textboxes in my row, now I'm going to attach some functions to my textbox events, for instant blur or keypress event:

            var TR = document.createElement('tr');
        TR.style.textAlign = 'center';

        //mission end date
        var TD = document.createElement('td');
        var span = document.createElement("span");
        span.innerHTML = "<input maxlength='5' type='text' width='50px' style='width:50px;' value=''/>";
        TD.appendChild(span);
        TR.appendChild(TD);
.......
        TR.appendChild(TD);
        document.getElementById('<%=tblData.ClientID %>').appendChild(TR);

I've create some other javascript functions that I'd like to attach them to these dynamically created textbox events, for instance:

function onBlur(){
.....
}

how can I attach onBlur to onblur event of these dynamically created objects? thanks

4
  • Easiest would probably be to use jQuery and its event delegation method on. Commented Sep 19, 2013 at 8:14
  • can I user JQuery here? isn't it possible with javascript? Commented Sep 19, 2013 at 8:15
  • 1
    or use var myInput = document.createElement("input"); myInput.addEventListener(...); mySpan.appendChild(myInput); Commented Sep 19, 2013 at 8:16
  • You can do it with Javascript, it's just more work. Commented Sep 19, 2013 at 8:18

1 Answer 1

2

replace

  span.innerHTML = "<input maxlength='5' type='text' width='50px' style='width:50px;' value=''/>";

with

 var input = document.createElement("input");
 input.style.width="50px";
 input.type="text";
 input.onblur = your_function_handler;
 span.appendChild(input);
Sign up to request clarification or add additional context in comments.

2 Comments

it worked thanks, but there is another problem, I must pass input object ID to my handler function, and then I use getElementById in this function to work on this dynamically created object, but it says object is null, what is going wrong?
you can add any data to dataAttributes. Like this jsfiddle.net/KdMWJ ; also i assume that i didn't fully understand your task, and you can use any other way to pass data to functions.

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.