user1882876
user1882876

Reputation: 45

JavaScript string replace in textarea

I'm trying to create a simple page that "corrects" YouTube's old embed code so that it works in PowerPoint 2010. If I hard code the embed code into a textarea on the page, it works fine, but if the user pastes the embed code into the text area, the javaScript doesn't seem to run.

Take a look here:http://jsfiddle.net/pch8N/

Here's what I have so far:

<p>Click the button to "fix" the old embed code</p>

<textarea rows="10" cols="60" id="demo"></textarea>
<br/>

<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML; 
var n=str.replace(/\/\/www.youtube/g,"http://www.youtube").replace(/version=3/g,"version=2");
document.getElementById("demo").innerHTML=n;
}
</script>

<button onclick="myFunction()">Try it</button>

Thanks for the help!

Upvotes: 4

Views: 15868

Answers (4)

selim
selim

Reputation: 1

        // hope this would be usefull
        // i used these codes for auto completing the texts in textarea.
        // other methods change all matching items before the selected text
        // but this affects only the text where caret on.
        // at first, i divided textarea.value into 3 pieces. these are ;
        // p1; until the 'searched' item, p2 after 'searched' item
        // and pa = new item that will replaced with 'searched' item
        // then, i combined them together again.

        var tea = document.getElementById(targetTextArea);

        caretPosition = tea.selectionStart - ara.length; //ara=searched item
        p1 = tea.value.substring(0,caretPosition);
            console.log('p1 text : ' + p1);
        p2 = tea.value.substring(caretPosition+ara.length,tea.value.length);
            console.log('p2 text : ' + p2);
        pa = yeni;  //new item
            console.log('pa text : ' + pa);

        tea.value = p1 + pa + p2;

        tea.selectionStart = caretPosition + yeni.length;
        tea.selectionEnd = caretPosition + yeni.length;

        tea.focus();

Upvotes: 0

null.point3r
null.point3r

Reputation: 1103

You should use value instead of innerHtml

function myFunction2()
{
var str=document.getElementById("demo2").value; 
var n=str.replace(/\/\/www.youtube/g,"http://www.youtube").replace(/version=3/g,"version=2");
document.getElementById("demo2").value=n;
}

Upvotes: 5

Voonic
Voonic

Reputation: 4775

Put your textarea inside form tag

Then use

var str=document.getElementById("demo").value; 

Upvotes: 0

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

var str=document.getElementById("demo").innerHTML; 

You should use .value and not .innerHTML

Upvotes: 0

Related Questions