简体   繁体   中英

Edit Text User inputs to textbox

so far I have this jsfiddle

<p>Click the button to remove http:// and www. from input box belove below:</p>

<textarea id="demo" name="comments" cols="25" rows="5">
    http://www.google.com
</textarea><br>
<input type="submit" value="Submit" button onclick="myFunction(),myFunction2()" />
</form>

<script>
function myFunction()
{
    var str=document.getElementById("demo").innerHTML; 
    var n=str.replace("http://","");
    document.getElementById("demo").innerHTML=n;
}

function myFunction2()
{
    var str=document.getElementById("demo").innerHTML; 
    var m=str.replace("www.","");
    document.getElementById("demo").innerHTML=m;
}
</script>​

It works fine with the text pre input but it will not change submitted text. I'm sure there's a simple answer, I'm just new to this and cannot work it out or find an answer.

You need to use .value of the textarea , not .innerHTML .

.innerHTML only looks at the generated HTML in an element. If the user types in something new, the source doesn't change.

But, the value does:

document.getElementById("demo").value = ...

Fixed in your fiddle:

http://jsfiddle.net/AbSh2/12/

A couple other pointers:

  • You don't need two functions to do that operation, as you can see it can be done in one.
  • You could use type='button' instead of a submit, since Javascript doesn't care about form submits (that only matters on the server, which receives POST and GET data. Javascript can't)

You can streamline your function even further without saving strings all over the place:

function myFunction() {
    var str=document.getElementById("demo").value;
    var n=str.replace("http://","");
    var m=n.replace("www.","");
    document.getElementById("demo").value=m;
}

works fine. You could even do

function myFunction() {
    document.getElementById("demo").value = 
        document.getElementById("demo").value.replace("http://","").replace("www.","");
}

but that gets a little jumbled IMO, so should be for learning purposes only :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM