I have the below Calculator Form which I'm creating in Magento that I would like to be able to use Magento's in-built JavaScript validations, even though I need to validate on a button click rather than a form submit.
Most of the logic is done through jQuery from a phtml file that I've added with a custom module, that has it's own frontend route, basically example.com/calculator.
Below is a simplified version of what I have:
<div id="calculator">
<form id="calculator_form">
<ul>
<li>
<h2><span class="count">1</span> Enter Values</h2>
<div class="row-section">
<div class="row-content">
<label>Length</label>
<div class="input-box">
<input type="text" class="height-val input-text required-entry">
</div>
</div>
<div class="row-content">
<label>Width</label>
<div class="input-box">
<input type="text" class="wall-width input-text required-entry">
</div>
</div>
</div>
</li>
</ul>
</form>
<button onclick="calculate();" class="button"><span><span>Calculate</span></span></button>
<div class="result">
<strong>Your Results</strong>
<p class="result-text"></p>
</div>
</div>
<script type="text/javascript">
function calculate() {
var calculator_form= new VarienForm('calculator_form', true);
// Callculations & Much More Form Logic is Here
// Includes a Lot of jQuery
jQuery('.result-text').html('Your results are:' + results);
}
</script>
I kind of have it working with var calculator_form= new VarienForm('calculator_form', true);
but it's not showing the validation message, it just highlights the first form field when I click on the Calculate button.
What am I missing? Any help would be really appreciated.
js/prototype/validation.js
is being loaded on the page.
UPDATE
I almost got it working with the below. I put var calculatorForm= new VarienForm('calculator-form', true);
into a separate script tag, and moved the button within the <form>
tags. The validation works properly but when I click on the button it refreshes the page when there are no validation errors.
<div id="calculator">
<form id="calculator-form">
<ul>
<li>
<h2><span class="count">1</span> Enter Values</h2>
<div class="row-section">
<div class="row-content">
<label>Length</label>
<div class="input-box">
<input type="text" class="height-val input-text required-entry">
</div>
</div>
<div class="row-content">
<label>Width</label>
<div class="input-box">
<input type="text" class="wall-width input-text required-entry">
</div>
</div>
</div>
</li>
</ul>
<button type="submit" onclick="calculate();" class="button"><span><span>Calculate</span></span></button>
</form>
<div class="result">
<strong>Your Results</strong>
<p class="result-text"></p>
</div>
</div>
<script type="text/javascript">
function calculate() {
// Callculations & Much More Form Logic is Here
// Includes a Lot of jQuery
jQuery('.result-text').html('Your results are:' + results);
}
</script>
<script type="text/javascript">
var calculatorForm= new VarienForm('calculator-form', true);
</script>