Ducain Ducain - 7 days ago 4
Javascript Question

Get innerHTML value from dynamically generated textbox (in javascript)

I'm using JavaScript to dynamically generate a dialogue box (it's a div element), containing a textbox and a submit button. I plan on submitting the value in the textbox to another page using AJAX.

My problem is that I can generate my textbox just fine, but I can't get the value from it. innerHTML comes back blank every time. I'm not sure what I'm doing wrong.

// Generate dialogue box using div
function create_div_dynamic()
{
//Create the div element
dv = document.createElement('div');

//unique tags
var unique_div_id = 'mydiv' + Math.random() * .3245;
var unique_textbox_id = 'mytext' + Math.random() * .3245;

//Set div id
dv.setAttribute('id',unique_div_id);

//Set div style
dv.style.position = 'absolute';
dv.style.left = '100 px';
dv.style.top = '100 px';
dv.style.width = '500px';
dv.style.height = '100px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';

//Create textbox element
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';

//Add textbox element to div
dv.appendChild(txt)

//Add the div to the document
document.body.appendChild(dv);

dv.innerHTML += '<input type="button" id="mysubmit" value="Read Textbox" onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';

}

Answer

Textarea elements don't have an innerHTML property. Just read the value property like you would with any other form element.

document.getElementById(unique_textbox_id).value