Frsti Frsti - 1 month ago 9
jQuery Question

Javascript populating hidden fields on mouseover - Before click

Looking for a solution to another problem I cam across the ability to run javascript on mouseover

I'd like to run this:

$(document).ready(function(){

function myPayment()
{

var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;

// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
}


When a user mouses over my submit button

When the script runs I'd like it to populate these fields which are then included in the form action

<input type="hidden" name="repay" id="repay_input" value="">
<input type="hidden" name="interest" id="interest_input" value="">


Right now it doesn't seem to work but this may be because I've missed a small thing or it just won't work entirely

Thank you - If anyone has a better idea on how to achieve my aim please let me know, I've tried PHP but no joy

Button for clarity

<button class="col-sm-4 enter-button" type="submit" name="submit" onmouseover="return myPayment()" value="Calculate">Calculate Payments</button>


Update:

I tweaked the javascript and the button but then missed off naming the form to match the reference in the JS

Also my mortgage calculations were WAY off due to the way the form collects % rate

Answer

Declare your function outside of jQuery's document.ready wrapper, and your button only needs to look like this:

function myPayment()
{
  var value = document.mortgagecalc.value_input.value;
  var rate = document.mortgagecalc.rate_input.value;
  var term = document.mortgagecalc.term_input.value;
  var deposit = document.mortgagecalc.deposit_input.value;
  var fee = document.mortgagecalc.fee_input.value;
  var totalloan = ((value + fee) - deposit) * 1 + rate;
  var totalinterest = (totalloan * 1 + rate) - totalloan;
  var months = (term * 12);
  var repay = totalloan / months;
  var interest = totalinterest / months;

  // Calculate mortgage payment and display result
  document.getElementById('repay_input').value = repay;
  document.getElementById('interest_input').value = interest;
}
<button onmouseover="myPayment()" ...></button>