Reputation: 155
I'm trying to write a character creation assistant for a tabletop game. Depending on character level, the number of Development Points a player can invest changes. This is my first major project in html5 and jQuery, but I thought it would be simple enough. I used advice from this question, but my values aren't updating. I've been screwing around with it in jsFiddle, but to no avail. I'm at my wit's end! Here's a link to my jsFiddle. The jsFiddle has only the relevant pieces of code that I want to work with. I got the rest of the form working.
HTML:
<strong>Level: </strong><input id="levelselect" type="number" min="0" max="20" />
You have <span id="DP"></span> DP to spend.
JS:
function calcDP() {
var level = parseInt($('#levelselect').val(),10);
var DPatZero = 400;
var DPatOne = 600;
var workDP = 0;
if (level === 0){
workDP = DPatZero;
}
else if(level == 1){
workDP = DPatOne;
}
else {
workDP = DPatOne + (level * 100);
}
var DP = workDP;
$('#DP').text(DP);
}
$('#levelselect').on('keydown keyup keypress', calcDP);
Upvotes: 0
Views: 80
Reputation: 386
First, you were binding the selector on the wrong element. Instead of binding the events on
$('#DP')
you should be binding them to
$('#levelselect')
Second, you want to catch every event, use the event 'change' for this to make sure not only keystrokes are being caught, but pastes and pressing the up and down arrows next to the imput are being caught as well:
function calcDP()
{
var level = parseInt($('#levelselect').val(), 10);
var DPatZero = 400;
var DPatOne = 600;
var workDP = 0;
if (level === 0)
{
workDP = DPatZero;
}
else if (level == 1)
{
workDP = DPatOne;
}
else
{
workDP = DPatOne + (level * 100);
}
$('#DP').text(workDP);
}
$(document).ready(function()
{
// Bind calcDP onchange to make sure every event is being caught.
$('#levelselect').on('change', calcDP);
// Call the onchange event to make sure the current value is evaluated
$('#levelselect').change();
}
Also, in your initial JSfiddle you used Mootools as the required framework on the left instead of jQuery.
See JS fidle for the full script: http://jsfiddle.net/9M4cD/4/
Upvotes: 0
Reputation: 318518
You bound the events to the wrong element. Use
$('#levelselect').on('keydown keyup keypress', calcDP);
instead of
$('#DP').on('keydown keyup keypress', calcDP);
and it will work.
Upvotes: 2