Reputation: 305
I'm new to jQuery, this will become very apparent.
I'm trying to basically learn jquery by applying it to small ideas.
In this case it's the Z-score formula in statistics.
z = x-mu/sigma
Here is how i'm approaching it in my jquery code.
$(document).ready(function() {
var x = $('input[name="xValue"]').val();
var mu = $('input[name="muValue"]').val();
var sig = $('input[name="sigmaValue"]').val();
var total = x - mu / sig;
function calculate() {
$('.result').html(total);
}
});
One concept that i have captured is to store your values in variables and then manipulate them that way.
What i'm struggling with is what to do with it next. In this case i want to output the result when an event is fired (onclick).
Here is my markup:
<section class="formula">
<div class="z"></div>
<div class="x">
<input id="xValue" type="text" name="x" autofocus>
</div>
<div class="mu">
<input id="muValue" type="text" name="mu">
</div>
<div class="sigma">
<input id="sigmaValue" type="text" name="sigma">
</div>
<div class="result"></div>
<button onclick="calculate()">Calculate</button>
</section>
Upvotes: 0
Views: 21541
Reputation: 641
Try this:
$("#btncalc").on('click', function() {
event.preventDefault();
var x = parseInt($("#xValue").val());
var mu = parseInt($("#muValue").val());
var sig =parseInt($("#sigmaValue").val());
var total1 = x - (mu / sig);
alert(total1);
$('div.result').html(total1);
});
Upvotes: 1
Reputation: 604
Well, i would like to point couple of mistakes here.
First, wrap your calculation logic inside the calculate
function like this.
function calculate() {
var x = $('input[name="xValue"]').val();
var mu = $('input[name="muValue"]').val();
var sig = $('input[name="sigmaValue"]').val();
var total = x - mu / sig;
$('.result').html(total);
}
Next, you are selecting your input
with name xValue
but in your html its name is only x
. Either change its name or use the selector input[id="xValue"
or $("#xValue").val()"
And finally, when you're using jQuery its better to avoid inline script. Use
$("#calculateButtonID").click(function(){
//calculate logic here...
});
Upvotes: 0
Reputation: 100205
you could do like: change your html as:
...
<button onclick="calculate()">Calculate</button>
...
to
..
<button type="button" class="calculate">Calculate</button>
....
and in js, a click handler for button with class calculate
:
$(document).ready(function() {
$(".calculate").click(function() {
var x = $('input[name="x"]').val();
var mu = $('input[name="mu"]').val();
var sig = $('input[name="sigma"]').val();
var total = x - mu / sig;
$('.result').html(total);
});
});
Demo jsFiddle
Upvotes: 1