Using JavaScript enhancements

Return to Introduction  Previous page  Next page

Moreover, the Product Options module allows you to write your own JavaScript code to validate complex product options rules, set up additional conditions, provide important details on selected options or introduce other enhancements. The code you provide will be executed when a customer makes an attempt to add a certain product option to his shopping cart. If the code returns the 'true' exit code, the product is being added to the customer's shopping cart, otherwise it is not.

<br>
Figure 8: Sample JavaScript code used to enhance product options functionality


Figure 8: Sample JavaScript code used to enhance product options functionality

Type the JavaScript code in the text box provided under the 'JavaScript enhancements' sub-title, and click on the 'Add' button to commit the code. Figure 8 demonstrates typical use of JavaScript code (for the definition of the product class used in Figure 8 see Figure 5).

JavaScript code can be used in combination with other product options, for example, text fields.

Example:

This example shows how to use JavaScript together with text fields. Customers will see two text fields on the product page: Login and Password. If they try to order the product without entering their login and password an alert box pops up with a request to complete the corresponding text fields.

Product page with 'Login' and 'Password' text fields

Product page with 'Login' and 'Password' text fields

Follow the instructions below to achieve the described effect.

Add 2 text fields as product options (for detailed instructions see the 'Defining product option classes' section). Name the fields Login and Password. Using the JavaScript enhancement form enter the following JavaScript code, making these fields required.

// obtaining the value of the Login option

var elm = product_option('Login');

// stripping all space symbols

var loginOpt = elm.value.replace(/ /g, '');

// checking the length of the Login option without space symbols

if (loginOpt.length == 0) {

    alert('Please fill in the Login field!');

    return false;

}

// obtaining the value of the Password option

var elm = product_option('Password');

// stripping all space symbols

var passwordOpt = elm.value.replace(/ /g, '');

// checking the length of the Password option without space symbols

if (passwordOpt.length == 0) {

    alert('Please fill in the Password field!');

    return false;

}

 

// all fields pass OK

return true;