smallbone smallbone - 12 days ago 5
HTML Question

JavaScript function doesn't change the textarea in Chrome&Firefox but works in IE

I've a web page which include a JavaScript function to convert the multiple lines to a comma separated data. Here is the code:



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.innerHTML = ctt;
} else {
incident_box.innerHTML = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>





It works fine in IE:
The line break replaced to comma

But it doesn't working as expected in Chrome and Firefox:
Line break replaced to comma at Dev Tool but it doesn't present on Chrome

Does any one know how to fix it?
Thanks

Answer

Use value property. innerHTML is for another purposes. Even textarea has the closing tag, the inner content is the textarea value:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
        function replaceSeperator() {
            var incident_box = document.getElementById("TextBoxIncidentID")
            var content = incident_box.value;
            //incident_box.innerHTML = content.replace(/\n/g, ",");
            var ctt = content.replace(/\n/g, ",");
            var lastchar = ctt.substr(ctt.length - 1);
            if (lastchar != ",") {
                incident_box.value = ctt;
            } else {
                incident_box.value = ctt.substr(0,ctt.length - 1);
            }
        }
    </script>
</head>
<body>
	<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>

Comments