Your new example code would never of changed the value entered by the user because it would of been executed before they have the opportunity to enter a value.
1. Replace the JavaScript in my previous point 1 with the following.
It defines an extra setup.toNumber(value, min, max) function which can be used to convert the value entered by the end-user into a number within a min / max range. It also changes the existing setup.feetAndInches(height) function to assume that the value passed to it has already been converted to a number.
setup.toNumber = function (value, min, max) {
var result = new Number(value.trim()).valueOf();
if (Number.isNaN(result)) {
result = 0;
}
return Math.max(Math.min(result,max), min);
};
setup.feetAndInches = function (height) {
/* If the height equals zero then display zeros. */
if (height === 0) {
return "0′0″";
}
/* Otherwise calculate the feet and inches then generate the String to be displayed. */
var feet = Math.trunc(height / 12);
var inches = height % 12;
return feet + "′" + inches + "″";
};
2. My previous point 2 stays the same, but make sure that the $pc.height property has previously been initialised to a value somewhere between 56 & 84 (inclusive) before it is passed as the defaultValue to the text-box
3. Replace the TwineScript / JavaScript in my previous point 3 with the following.
It converts the text-box into one that supports numbers (on supporting web-browsers) and assigns min & max values which will limit the scrolling up/down feature of the numeric input (1). It has also been change to use the new function from the new point 1 and importantly it now updates the related story variable which is necessary due to the fact that the setup.toNumber(value, min, max) function can alter the value that the end-user entered.
<<script>>
/* Handle validation of the PC's height. */
$(document).one(':passagerender', function (ev) {
$(ev.content)
.find('#textbox-pcheight')
.attr({
'type' : 'number',
'min' : 56,
'max' : 84
})
.on('change.feet-and-inches', function () {
var height = setup.toNumber(this.value, 56, 84);
this.value = height;
State.setVar("$pc.height", height);
$('#feet').html(setup.feetAndInches(height));
})
.on('keypress.feet-and-inches', function (ev) {
// If Return/Enter is pressed then update the ddisplayed feet & inches.
if (ev.which === 13) { // 13 is Return/Enter
var height = setup.toNumber(this.value, 56, 84);
this.value = height;
State.setVar("$pc.height", height);
$('#feet').html(setup.feetAndInches(height));
}
});
});
<</script>>