Search code examples
javascripthtmlinputreplacegetelementsbytagname

Javascript change text of all inputs


I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do

<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace "R$" with "" in the field below:</p>

<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>

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

<script>
function myFunction()
{
var x=document.getElementByTagName("input")

for(var i = 0; i < x.length; i++) {

  var str=x[i].innerHTML; 

  var n=str.replace(",",".");
  var n1 = n.replace("R$ ","");

  document.getElementById("demo").innerHTML=n1;
 }


}
</script>

</body>
</html>

So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.


Solution

  • These are the needed steps - at least step 1 through 3

    1. moved the script to the head where it belongs
    2. changed getElementByTagName to getElementsByTagName, plural
    3. get and change x[i].value
    4. chained the replace

    DEMO

    <!DOCTYPE html>
    <html>
    <head>
    <title>Replace example</title>
    <script>
    function myFunction() {
      var x=document.getElementsByTagName("input"); // plural
    
      for(var i = 0; i < x.length; i++) {
        var str=x[i].value; 
        x[i].value=str.replace(",",".").replace("R$ ","");
      }
     }
    </script>
    </head>
    
    <body>
    
    <p>Click the button to replace "R$" with "" in the field below:</p>
    
    <input id="demo" value="R$ 1223,43"></input>
    <input id="demo1" value="R$ 134523,67"></input>
    <input id="demo2" value="R$ 12453,41"></input>
    
    <button onclick="myFunction()">Try it</button>
    
    
    </body>
    </html>