I have now spent literally days trying to debug a simple replace in javascript and it is driving me crazy. Would appreciate any help.
When I create a simple html file with a javascript function in the header and call to function in body, I can grab the contents of an element and replace certain characters of innerHTML such as line breaks using replace method. I can also do this with jsfiddle.
toedit = toedit.replace(/\n/g, '<br />');
However, in the actual application where I want to use it, where the script is in the header of the page and the html is placed in a div on the page through some ajax, it fails. Can anyone spot problem?
Following works in HTML page or JSFiddle
<html>
<head>
<script type="text/javascript">
function editText(editThis)
{
alert(editThis);
//alert("hi");
var toedit = document.getElementById(editThis).innerHTML;
// alert(toedit);
toedit = toedit.replace(/\n/g, '<br />');
alert(toedit);
}
</script>
</head>
<body>
<textarea id="text" name="text" rows=9 cols=30 placeholder="Type Notes">A whole bunch
of text with
line breaks goes here</textarea><a href="#" onclick="editText('text');return false;">edit</a>
</body>
</html>
Following script does not run with line that has * next to id. Does work with that line deleted. Script breaks when line merely commented out.
In header of page:
<script type="text/javascript">
function editText(editThis)
{
alert(editThis);
//alert("hi");
var toedit = document.getElementById(editThis).innerHTML;
alert(toedit);
toedit = toedit.replace(/\n/g, '<br />'); //****problem line
alert(toedit);
}
</script>
//following function called from page, fills div with html that includes link to above js
function loadSteps(id)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("stepsDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsteps.php?id="+id,true);
xmlhttp.send();
} //end function
getsteps.php called from above js function
echo '<textarea id="text" rows=9 cols=30 placeholder="Type text">'.$text.'</textarea><a href="#" onclick="editText(\'text\');return false">edit</a>
'); No idea why extra \ is necessary in my environment but not in the jsfiddle or in a simple html file but anyway got it to work. Thanks for inspiration all. – user1904273 Dec 28 '12 at 03:26