2

My code

<!DOCTYPE html>
<html>
<body>

<input type="text" id="text" value=""><br>


<button onclick="myFunction()">Submit</button>


<script>
function myFunction() {

var str = document.getElementById("text"); 
var res = str.replace("1", "2");
document.getElementById("text") = res;


}
</script>

in input field i am taking some input from user on (click) submit i want to replace all 1 with 2 and i want to display result in same field but its not working..

0

3 Answers 3

3

You need to get the value

function myFunction() {
    //getElementById returns dom object
    var el = document.getElementById("text");

    //you want to replace its value
    var str = el.value;

    //use a simple regex to replace all instances
    var res = str.replace(/1/g, "2");

    //set the value property of the target element
    el.value = res;
}

Demo: Fiddle, short version

Sign up to request clarification or add additional context in comments.

3 Comments

Perfectly Working ...Thanks But i Have 1 More lil Question i want to replace [img] as <img src="
what should be the value of src=
can be something like 'some text [img] with image'.replace(/\[img\]/g, '<img src="" />')
1

This is what you want:

function myFunction() {
  var inputElt = document.getElementById("text");
  var res = inputElt.value.replace("1", "2");
  inputElt.value = res;
}

Comments

0

Your line:

document.getElementById("text") = res;

instead, should look like this:

document.getElementById("text").value = res;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.