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
Mircea MarinMircea Marin 

How can you trigger an Apex Method, a reRender and a JavaScript function with one button press

Hi everyone,

We have a method that sets the value of a variable / field called {!input}. This value is then read in a JavaScript function which immediately sets the value of another field / variable {!output}. The problem is that in order to have the value of {!input} available for the JavaScript to read, the form needs to be reRendered first.
 
Can this be achieved with just one commandButton?

Apex Class
public String input {get; set;}
      public String output {get; set;}
public void generateInput() {
      input = ‘some calculated value’;
}
VF Page
<apex:page>
<script type="text/javascript">
    function generateOutput(){
        var input = document.getElementById('{!$Component.input}').value;
        if(input) {
        var output = input + ‘some other value’;
        document.getElementById('{!$Component.output}').value = output;
        }
    }
</script>
<apex:form id="myForm">
    <apex:inputText id="input" value="{!input}"/>
    <apex:inputText id="output" value="{!output}"/>
    <apex:commandButton value="Generate Input" action="{!generateInput}" reRender="myForm"/>
    <apex:commandButton value="Generate Output" onclick="generateOuput()" reRender="myForm"/>
</apex:form>
How can the 2 actions be done with one click? -> if we try to combine the action and onclick of the 2 commandButttons and use them on the same button, on the first click of the button the output is created and only on the second click the input.

Thanks,
Mircea
Sampath SuranjiSampath Suranji
Hi,
You can combine the js function with the apex method.
In the generateInput apex method, do the calculation part and set the both !input and !output variable values.
public void generateInput() {
        input = 'input some calculated value';
        output = input + 'some value out';
    }
regards