Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to call a Javascript function as well as issue a backend call at the moment a button is clicked.

This is my code right now :

<apex:commandButton value="Search" action="{!objectCollection}" style="margin-left:10px" reRender="source_search">
 <apex:param name="source" value="true"/>
 <apex:param name="target" value="false"/>
</apex:commandButton>

Is this possible?

share|improve this question

Yes, you can.

You can use the onclick attribute like below.

<apex:commandButton value="Search" action="{!objectCollection}" 
  onclick="callJSFunc()" 
  style="margin-left:10px" reRender="source_search">
  <apex:param name="source" value="true"/>
  <apex:param name="target" value="false"/>
</apex:commandButton>

UPDATE

Based on your comments below, you want to call both JavaScript and Controller's function only if the input is valid. You can achieve this with following code:

<apex:commandButton value="Search" action="{!objectCollection}" 
  onclick="if(!isInputValid()){return false}else{callJSFunc()}" 
  style="margin-left:10px" reRender="source_search">
  <apex:param name="source" value="true"/>
  <apex:param name="target" value="false"/>
</apex:commandButton>

The idea is that the isInputValid() is also a JS function that will validate the input and return true if everything is valid, and false if the input is invalid. If the isInputValid() returns false, neither the controller's function, nor your JavaScript function in the else statement will get called.

share|improve this answer
    
Thanks! Another question. In this case, regardless of good/bad input when the button is clicked both the Action and onclick will execute, correct? Is there any way call the backend function in my controller via the javascript function? Because what I want to do is verify good input before I send it to the backend function – user2582622 yesterday
    
@user2582622 please, see my update. – smukov yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.