function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Alex Li 26Alex Li 26 

Update input value with Javascript using $Component

I'm trying to update a input field when the value of an another field changes using javascript.
I need to hold the id of the field to update in a variable because the input to update changes depending on the id passed as parameter but I try to read or write the new value (not in sample code) with the variable I get an error. 
Whereas, when I write fully the id (like "toUpdate1") I have no issue. 
(The code might have a typo but basically when I try to read an input value selected with a variable, it's not working but when the id is fully written, no problemo as expected)
<apex:page id="page">
  <apex:form id="form">
    <apex:inputField id="aField" value="Changing value" onchange="updateInputValue(toUpdate1)"/>
    <apex:inputField id="toUpdate1" value="Initial value"/>

    <apex:inputField id="aField" value="Changing value" onchange="updateInputValue(toUpdate2)"/>
    <apex:inputField id="toUpdate2" value="Initial value"/>

    <apex:inputField id="aField" value="Changing value" onchange="updateInputValue(toUpdate3)"/>
    <apex:inputField id="toUpdate3" value="Initial value"/>
  </apex:form>

  <script>
    function updateInputValue(fieldToUpdate) {
      // Separate { from ! to avoid apex error
      var idFieldToUpdate = "{" + "!$Component.page.form." + fieldToUpdate + "}";

      console.log(document.getElementById(fieldToUpdate).value); // Error cannot read value from "null"

      console.log(document.getElementById("{!$Component.page.form.toUpdate1}").value); // OK
    }
  </script>
</apex:page>