cafekuktem
cafekuktem

Reputation:

problem with dom createelement and innerhtml

/*************** javascript *****************/

function here(getValue) {

    alert(getValue)
}

function aaa() {

    document.getElementById('asd').innerHTML = '<input type="text" name="textfield" onkeyup="here(this.value)" />'
}

function aaa2() {

    var temp = document.getElementById('asd').innerHTML
    document.getElementById('asd').innerHTML = temp+'<input type="text" name="textfield" onkeyup="here(this.value)" />'
}

function dom() {

    var zzz = document.getElementById('asd')

    var inp = document.createElement('input')
    inp.type = 'text'
    inp.name = 'textfield'
    inp.onkeyup = function() {here(this.value)}

    zzz.appendChild(inp)
}

/************************************/

<div id="asd"> 
    <input type="text" name="textfield" onkeyup="here(this.value)" />
</div>

<input type="button" name="Button1" value="Button1" onclick="aaa2()" />
<input type="button" name="Button2" value="Button2" onclick="dom()" />

need some help...

i create a textfield using dom by click Button1, then combine with textfield using innerhtml by click button2.

the problem is after combine the dom createelement with innerhtml, the textfield created by dom cannot call the javascript function...

anyone have a solution...

thanks...

Upvotes: 1

Views: 1819

Answers (2)

Gab Royer
Gab Royer

Reputation: 9806

Your problem is with this

inp.onkeyup = function() {here(this.value)}

You can't define onkeyup like this if it didn't existed before. Plus, this argument must be a string (basically, the Javascript code to execute)

inp.setAttribute('onkeyup','here(this.value)');

Upvotes: 1

Jonathan Fingland
Jonathan Fingland

Reputation: 57157

I don't see anything wrong with the code as to how it works (maybe not best practices, but it works).

Tested and working in firefox 3.5. See test page at http://ashita.org/StackOverflow/innerhtml.html

Upvotes: 1

Related Questions