[SalesForce] On click Javscript on Custom Button

I have a related list ( custom object ) on Opportunity record. When I click on New button of the custom object from the related list of the opportunity , I want to check the value of some field on the opportunity record based on which I should either redirect to another visualforce page else I should show some message. Can this be achieved using OnClick Javascript functionality on the Custom Button?
code snippet will be useful.

Thanks

Best Answer

This can be accomplished using a custom button that can be displayed on the related list. The JavaScript on that button will look similar to this:

// test the merge field's value against the value that you expect
var condition = '{!Opportunity.YourField}' === 'Some Value';

// if the condition is true, redirect. Otherwise alert.
if (condition) {
    window.location = '/apex/YourNextPageName';
} else {
    alert('These are not the droids you are looking for...');
}

You can also replace the /apex/YourNextPageName with a URLFOR function.