user667925
user667925

Reputation: 13

Set x.innerHTML as INPUT truncating value string

I have:

function edit(recRef)
{
var recID=recRef+'_what';
var x=document.getElementById(recID);
var y=(x.innerHTML);
alert(y);
x.innerHTML="<INPUT type='text' value="+y+" />";
}

The original recID element is a TD with a string in it [e.g. "This string"].

At the end of calling the edit function the an INPUT tag type text is inside the TD tag, but the string is truncated to only the first word [e.g. in the example it shows "This" but not "This string"].

Even more interesting, if the string in the TD was originally empty after calling edit the value on the INPUT tag is a single forward slash "/".

What is going on here?

Upvotes: 1

Views: 959

Answers (3)

Michael Gillette
Michael Gillette

Reputation: 310

Built atop Shadow's response, heres what a cross browser solution might look like

function edit(recRef) {
    var isIE/*@cc_on=1@*/;
    var el = document.getElementById(recRef);
    var input = document.createElement( isIE ? "<input type='text'>" : "input" );
    input.setAttribute("value",el.innerHTML)
    el.replaceChild(input,el.childNodes[0]);
}

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66388

Try this code instead:

var recID = recRef+'_what';
var oRecord = document.getElementById(recID);
var sHTML = oRecord.innerHTML;
var oInput = document.createElement("input");
oInput.type = "text";
oInput.value = sHTML;
while (oRecord.childNodes.length > 0)
   oRecord.removeChild(oRecord.childNodes[0]);
oRecord.appendChild(oInput);

This will directly insert new DOM element instead of messing with the literal HTML.

Upvotes: 1

Ashwini Dhekane
Ashwini Dhekane

Reputation: 2290

You forgot ' in the value attribute

x.innerHTML="<INPUT type='text' value='"+y+"' />";

Upvotes: 1

Related Questions