1

I have a variable whos value i am setting on click of command button. I have a 2nd command button and i want to use the new value of the variable set previously. vf:

  <apex:commandButton styleclass="btn btn btn-primary" id="generate"  action="{!generate}" value="Generate" style="margin-top:20px;margin-left:5px;" reRender="" oncomplete="return false;"/>
  <apex:commandButton styleClass="btn-primary" onclick=" if(!fncValidate()){return false;}" id="vieweLineStatusButton" value="Submit" disabled="false" reRender="" oncomplete="return false;" />

script:

<script>
    function fncValidate(){
    var one = '{!first}';
        alert(one);
     return true;   
    }
</script>

apex:

 public String first{get; set;}
 public PageReference generate(){
 first = '1111';
 return null;

 }

i am always getting null in my js

1 Answer 1

1

Problem is that given script code is evaluated only once during page load. That cause JS to be executed only once, so as long as first in controller is not set in constructor or getter, then it will be assigned to JavaScript variable one as null, and will not be updated.

There are few ways to keep those records in sync. One of that is using reRender action to rerun JS code after controller method execution, after visualforce state got updated apex variable from server. Personally I do not like that method because it can easily cause JavaScript issues, which I prefer to stay clear and concise.

Another option will be using <apex:inputHidden /> and JS to get updated variable from that. Nice example can be found here.

In your case, that may look like next (JS pseudocode):

Visualforce

<apex:form>
  <!--INITIAL CODE -->
 <apex:commandButton styleclass="btn btn btn-primary" id="generate"  action="{!generate}" value="Generate" 
                     style="margin-top:20px;margin-left:5px;" reRender="" oncomplete="return false;"/>
 <apex:commandButton styleClass="btn-primary" onclick=" if(!fncValidate()){return false;}" 
                     id="vieweLineStatusButton" value="Submit" disabled="false" reRender="" oncomplete="return false;" />
<!--END INITIAL CODE -->
<apex:inputHidden value="{!first}" id="veryUniqInputId"/>
<script>
   var $j = jQuery.noConflict();

   function fncValidate() {
     var one =  $j("element[id$='veryUniqInputId']").val();
     alert(one);
     return true;   
   }
  </script>
</apex:form>

There are other options, like remoting or web service execution, but that require more logic to be implemented.

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.