attribute maxlength of input field is changing, but input doesn't care - javascript

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.
I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?
my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters(); //this gets called often
EDIT: http://jsfiddle.net/mDw6f/

EDITTTT:
You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)
Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.
Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.
Cheers
Real Fiddle Example

Try using this fiddle:
Working Demo
Use the html input like I did in the code, no need to specify the maxlength attribute to it.
<input type="text" class="my_input_class"/>
and the script
my_var = 25; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters();

Related

Acrobat PDF calculation with checkbox

I've created a PDF form to help create an estimate for plumbing work. There are various lines that the contractor fills in for quanity, cost of the item and then automatically calculates the price for that line; this works fine.
But now I want to add a checkbox to the line that the customer would check if they actually want that work to be done. If they check the box then the price would appear in the final field, otherwise it would display 0.
My fields are:
QtyRow2 ItemCostRow2 CheckboxRow2 PriceRow2
I've tried this Javascript code in the Calculation tab for the PriceRow2 field, but it displays "0" in the price field whether the checkbox is checked or not.
var oFldQty = this.getField("QtyRow2");
var oFldItem = this.getField("ItemCostRow2");
if (this.getField("CheckboxRow2").isBoxChecked(0)) {
nSubTotal = oFldQty.value * oFldItem.value;
} else {
nSubTotal = 0;
}
event.value = nSubTotal;
How should I modify this to get it to work?
If this is the whole code in the calculation, it would be way safer to define nSubTotal; otherwise, it gets defined as a global variable, and can behave strangely.
Also, whenever this calculation runs, and the test results to false, nSubTotal is set to 0. That means, you have to define nSubTotal, and then add to it while you work through the form.
If you want to simply have a result in the field, there is no need to do the detour via a variable; you can set event.value in the true and the false path.
For a single checkbox, it is IMHO easier to use its value (or its "unchecked" value for portability of the code reasons). This leads to the following code snippet:
if (this.getField("CheckboxRow").value != "Off") {
// box is checked
event.value = oFldQtyty.value * oFldItem.value ;
} else {
// box is unchecked
event.value = 0 ;
}
And that should do it.
However, as you have a table, it is best practice to consolidate all calculations into one single script, which can be attached to a hidden read-only field which is not even involved in the calculation itself. This gives you much better overview and control over the calculation, and prevents calculation order errors.

What's wrong with my delete button on my HTML/Javascript calculator

I'm trying to make a simple calculator using HTML, CSS, and Javascript. I'm done with the calculation part and the design but I'm having a hard time with my DEL button. My DEL button is supposed to backspace the last key pressed on the calculator.
I made a function called del() on my .js and this is what it looks like so far:
function del()
{
document.getElementById("dis").value = (document.getElementById("dis").value.getLength) - 1;
}
"dis" is the id of my calculator's display.
try this one
var val = document.getElementById("dis").value;
if(val.length > 0){
val = val.substring(0, val.length - 1);
document.getElementById("dis").value = val;
}
Because your code is setting the display's value to:
(document.getElementById("dis").value.getLength) - 1
Which is the number of digits (string length) of the displayed value minus one, so if the value was "500", it would set it to 2 (3-1). Clearly not what you want.
What you want is to get the value, cut it down to just the characters you want (probably with substr()) and then re-set the value to that string.
.getlength is undefined. If you want the length of the string, you should use str.length. Anyway, if you want to remove the last character, use this
str=str.substr(0,-1);
or, for your code
document.getElementById("dis").value = document.getElementById("dis").substr(0,-1);
you need to use String operations...MDN
something like this should work:
document.getElementById("dis").value = document.getElementById("dis").value.slice(0, -1)

Javascript removing decimals in knockout binding

I've seen there are quite a few questions about decimal precision and display in Javascript. the thing is that I came to a solution that I thought it was gonna be enough for me'
The key thing is that I'm trying to parse to a string to round and then back to numbers using expressions like this.
return parseFloat(num.toFixed(2));
But there are some cases that it doesn't work as expected. To be honest I'm not sure if it has to do with the way I'm using ko or the javascript code for parsing I put in place. But let's say that in the below fiddle you type 14.385 in the upper text box, both fields will be properly rounded and will display the correct number of decimals, but without deleting the number you add 3333 (that means 14.393333) and the upper one won't be rounded. That's just an example because there are some strange behaviours.
Yo can see the fiddle here http://jsfiddle.net/RTexF/
Thanks
Edit. I add the code as per judgeja indication (I didn't understand the reason to ask for a code when you link fiddle, I see the point now)
The script
var decimalValue = 0.25;
function ViewModel() {
var self = this;
self.submittedValue = ko.observable(decimalValue);
self.percentage = ko.computed({
read: function() {
alert('read');
if (isNaN(parseFloat(self.submittedValue())))
return '';
var num = self.submittedValue() * 100;
return parseFloat(num.toFixed(2));
},
write: function(value) {
alert('write');
value = isNaN(value) ? '' : parseFloat((value / 100).toFixed(4));
self.submittedValue(value);
},
owner: self
});
}
ko.applyBindings(new ViewModel());
And the html
<p><input data-bind="value:percentage"></input></p>
<p><input data-bind="value:submittedValue"></input></p>
EDIT:
Know that it's an old one but I wanted to note that adding this to the write method
self.percentage.notifySubscribers(value);
it fixes the issue (ideally we could check against the current value and just notifiy if it actually changes)
Fiddle : http://jsfiddle.net/RTexF/1/ and http://jsfiddle.net/RTexF/2/
It may help you to think about this if you put an alert("read") in the read: and an alert("write") in the write: and then run your example again.
When you change the top box the first time the bottom box is written to through the write and then the top box is re-computed as the submittedValue observable has changed and you'll see the read for percentage being hit.
Next time you edit the top box the write will be hit again as we're changing the value, which makes sense, but since the submittedValue isn't changed, then the read won't happen again as the observable it depends upon won't have changed.

Auto Updating the Value of an Input Field

I'm not sure how simple or how complicated this question may as I am just learning javascript, but here it goes.
Say I have an input field:
<input type="text" value=""/>
I am trying to write a javascript function that checks the input value every time a space is entered, and then edit the value live while the user is typing.
For example, say I start typing: hello, how are u
After I hit space following 'u', I would like to replace 'u' with 'you'.
So, if anyone who be so kind, where do I start here? This may be ironic because I see the text I am typing right this instant being updated just to the bottom of this textarea. However, I am trying to get it to update in the field itself.
Thanks!!!
You don't necessarily need jQuery to do this, but it is a little more work with vanilla JS. First, give your input an ID:
<input id="ValueField" type="text" value="" />
Then add an event listener:
var field = document.getElementById('ValueField');
field.addEventListener('keyup',function(e){
if(e.keyCode==32){
// do your stuff
}
});
There are a million ways to detect change, but first thing that comes to mind is a function:
var field = document.getElementById('ValueField');
field.addEventListener('keyup',function(e){
if(e.keyCode==32){
field.value = replaceValues(field.value);
}
});
function replaceValues(fieldval){
var baditems = [' u ',' i '],
newitems = [' you ',' I '],
length = baditems.length;
for(var i = length; i--;){
fieldval = fieldval.replace(baditems[i],newitems[i]);
}
return fieldval;
}
Just build out the array of bad and new items to be the same length with their order matching and you should be good. This way you can replace as many items you want, and should run pretty quickly.
EDIT
Might help if I have the function return something! Here is a jsFiddle to show example. Also, I had to add spaces around the u and i because otherwise it would just match any instance of the letter.
if you are using jquery, look at this: https://stackoverflow.com/a/2249215/146602
good way to detect if a space character is being used.

jquery masked input plugin to not clear field when errored

I'm looking at the http://digitalbush.com/projects/masked-input-plugin/
I'm calling it like this:
$(control).mask('999-999-9999');
And I don't want it to throw away the users input if something is wrong, e.g. they haven't finished
[407-555-____]
If you leave the field after having typed this much, it clears it. I'd like to leave it so they can finish later.
I'm new to jQuery, and I've looked through his source, but I can't find any way to do that, nor can I find any way to edit it to accomplish what I want, because the code is arcane to my eyes.
Set autoclear option to false.
$(control).mask('999-999-9999', {autoclear: false});
It looks like I should just make the whole mask optional:
mask('?999-999-9999')
That way the control thinks what the user has is "valid" and I can continue. Even though it isn't really the optional part of the mask.
You should delete statement input.val(""); in checkVal() function for a proper solution.
If you're using minified version, you should search and delete statement:
if(!a&&c+1<i)f.val(""),t(0,k);else
Try update file jquery.maskedinput.js
In function function checkVal(allow) set parameter allow on true. Its help for me.
function checkVal(allow) {
allow = true; ///add this command
//..............
}
In addition to removing the input.val("") in checkVal() you can also change the call to clearBuffer.
In the original code it is: clearBuffer(0, len); removing all user input.
if you change this to clearBuffer(lastMatch + 1, len); the user input will be displayed, followed by the mask placeholders that are still needed to complete correct input.
I have also added a user message in the .bind. This works for us, as we are using the MaskedInput for exactly one type of input. I'm checking for any input going further than position 7, because that's where the user input starts.
Here is what I did:
.bind("blur.mask", function() {
// find out at which position the checkVal took place
var pos = checkVal();
// if there was no input, ignore
if (pos <=7) {input.val(""); clearBuffer(0, len);}
// if the user started to input something, which is not complete, issue an alert
if (pos > 7 && pos < partialPosition) alert("Tell the user what he needs to do.");
if (input.val() != focusText)
input.change();
})
Adding Placeholder could solve the problem.
$(control).mask('999-999-9999');
Add an empty place holder into mask. see below
$(control).mask('999-999-9999', { placeholder: "" });
which would replace _ on the input text field by default. so there would bot be any _ left if the input length is dynamic and not fixed.
Looking for into the pluging script the unmask method.
$('#checkbox').unmask();

Categories

Resources