0

I have 2 command buttons on my vf page:

<apex:commandButton onclick="saveAndnewmethod()" value="Save and New"/>
<apex:commandButton onclick="savemethod()" value="Save"/>

and they call different js method. but these js methods have a lot of common lines of codes that I want to merge it into just one method.

function save(){
  //...common lines
  if(someValidations == true){
  $('.savebtn').prop('disabled', true);
  save_ACC_Cont();//this is an action function of button save
  }
}
function saveAndnewmethod(){
//...common lines
  if(someValidations == true){
    save_and_new();////this is an action function of button save and new
    $('.savebtn').prop('disabled', true);
  }
}

what i would want to do is merge the function and detect which button is clicked so that i would only call one js method and avoid repetitive lines. how will i do it? hope someone could help...

2
  • you can pass a paramter to the method to find which button has clicked Jul 16, 2018 at 6:22
  • or you can use event to identify the button
    – Ratan Paul
    Jul 16, 2018 at 6:29

2 Answers 2

3

You can pass the parameter in the Javascript function and then check the value for both the case. For example Pass Save from the save button and pass SaveAndNew from save and new button.

Below will be the code for command button

<apex:commandButton onclick="commonFunction('SaveAndNew')" value="Save and New"/>
<apex:commandButton onclick="commonFunction('Save')" value="Save"/>

And below will be the javascript code

function commonFunction(buttonClicked){
    //.. Common Lines
    if(buttonClicked === 'SaveAndNew'){
        //.. save and new logic here
    }else if(buttonClicked === 'Save'){
        //... logic here
    }
}
2

Another way use event to identify the button

<input type="button" id="btn1" onclick="commonFunction(event)" value="Save and New"/>
<input type="button" id="btn2" onclick="commonFunction(event)" value="Save"/>

And in javascript use e.target.id

function commonFunction(e){
    //.. Common Lines
    if(e.target.id === 'btn1'){
        //.. save and new logic here
    }else if(e.target.id === 'btn2'){
        //... logic here
    }
}

Just remember if you use apex button it will have the form page pageblock etc ids as well

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .