I am trying to build the user interface for an online character creator app using jQuery. I am trying to randomly generate character stats with one button click. This is my first time using jQuery in a non-trivial application.
The issue is that when I click the button, not numbers are generated inside the forms. If I remove the disabled attribute it still doesn't work, so I know that isn't the problem.
If I was to take a stab at it I would guess $() in jQuery doesn't like taking variables, but if that is the case, I don't know how the right way to do this would be. The example for filling out multiple forms with one click on the jQuery site isn't useful for this purpose since I need to make sure the dice function is called separately to fill each form.
My javascript code looks like this:
$(document).ready(function(){
//stats as an array
stats = ["#smarts", "#rwp", "#driving", "#cool", "#bod", "#luck", "#looks", "#bonk"];
//roll dice function
function dice (x, n, y) {
var result = 0;
for(i = 0; i < x; i++) {
result = result + Math.floor((Math.random() * n) + 1);
}
result = result + y;
return result;
}
//roll each stat function
function rollStats(stats) {
for(stat in stats) {
$(stat).val(dice(1, 6, 0));
}
}
//on button click roll each stat
$("#stats").click(rollStats(stats));
});
And for reference the relevant part of my html form looks like this:
<form class="create-teenager">
Smarts:
<input type="number" name="smarts" id="smarts" disabled />
<br/><br/>
Relationship with Parents:
<input type="number" name="rwp" id="rwp" disabled />
<br/><br/>
Driving:
<input type="number" name="driving" id="driving" disabled />
<br/><br/>
Cool:
<input type="number" name="cool" id="cool" disabled />
<br/><br/>
Bod:
<input type="number" name="bod" id="bod" disabled />
<br/><br/>
Luck:
<input type="number" name="luck" id="luck" disabled />
<br/><br/>
Looks:
<input type="number" name="looks" id="looks" disabled />
<br/><br/>
Bonk:
<input type="number" name="bonk" id="bonk" disabled />
<br/><br/>
<button id="stats">Roll Stats</button>
</form>
Aucun commentaire:
Enregistrer un commentaire