Is there any smart, minimalistic way to always show the prefix (positive, negative) of a number in a HMTL input field? (e.g. +1, 0, -1)
I have only found s solution for PHP:
How to prefix a positive number with plus sign in PHP
I have to use <input type="text"> since there are different implementations for text=number in different browsers: Localization of input type number
Why am I doing this?
I have an input field that shows the percentage that can be added (or subtracted) to a certain value.
Basevalue: 10
Mofification %: +10
Results: 11
The easiest way would be using some basic javascript. Add a script at the end of your HTML page (before the body closing tag) then give to the input an id, for example prefixedInput. Then you can write your little script
var inputField = document.getElementById("#prefixedInput");
var inputFieldValue = inputField.value;
if (inputFieldValue > 0) {
inputField.value = "+" + inputFieldValue;
}
if (inputFieldValue < 0) {
inputField.value = "-" + inputFieldValue;
}
Now, that works in a way that isn't really useful because this function will be executed just one time when the page will load, so if you have assigned to your input a value, this will be prefixed with its sign. However if you want to bind this behaviour to some actions (e.g. prefixing the value even if the user inserts the value after the intial page load) you will be forced in using event listeners.
Related
I built a calculator in ReactJs. And i would like to prevent the user from entering more than one decimal element eg 2..3 Anytime a user does this i'd like to replace all the decimal elements with a single one. So 2..3 would become 2.3
This is how i am trying to achieve this but it doesnt work
if (calc.input.match(/\.{2,}/g)) {
setCalc(calc.input.replace(/\.{2,}/g, "."));
}
setCalc is the hook i'm using to change state.
This should help. It basically keeps the input from happening if we already find a decimal in the string already when hitting a key.
const text = document.querySelector('input[type="text"]');
text.addEventListener('keypress', e => {
// if the text already includes a decimal, and our current key is a decimal, prevent the new key from being added.
if (text.value.includes('.') && e.key == '.') e.preventDefault();
});
<input type="text">
Remembered that strings are immutable and so to change the value of calc.input I would have to reassign it to itself. And so this approach worked for me for this particular use case.
Note that it doesnt prevent input in the form 9.9.9
if (calc.input.match(/\.{2,}/g)) {
setCalc(calc.input = calc.input.replace(/\.{2,}/g, "."));
}
Try this...
var S='456...........876';
S=S.replace(/\.+/g,'.'); // I escape the period with a slash and place the + next to it to mean "all".
document.write(S);
The short version: I work in a hospital and am attempting to create a safer, more efficient downtime version of the forms we send with blood components for transfusion. Currently we handwrite or type the donor identification number (DIN) and the product code of the unit onto this form, but ideally these are scanned, as they are ISBT 128 barcodes on the unit.
Scanning a DIN gives me ~=W11512003927826 - I would like to have the first two characters (non-alphanumeric) removed, and if possible, the last two. I've been able to accomplish the second task by simply limiting the character input of the field, which is standard and should work fine.
This also applies to the product code, which scans as ~=<E0785V00 and does not need the first three characters.
I've tried a few methods including some Javascript that was supposed to limit the field to only alphanumeric characters, which I assume is probably the simplest way to handle all of this, but either the code was not in the correct syntax for Adobe or I implemented it incorrectly. I am not familiar with JS at all and am just learning form creation.
If anyone has any advice I'd appreciate any help at all. Thanks in advance!
Edit: So far I've tried these three. I'm using these as an action (run a javascript) on mouse exit and also tried on blur.
const alphanumeric = /[a-zA-Z0-9]/g;
const string = "abc-ABC-012";
const result = string.match(alphanumeric).join("");
console.log(result); // abcABC012
const nonalphanumeric = /[_\W]/g;
const string = "abc-ABC-012";
const result = string.replace(nonalphanumeric, "");
console.log(result); // abcABC012
const string = "aa-aa";
const result = string.slice(2, -2);
console.log(string); // aa-aa
console.log(result); // -
I recommend you setup "On Blur" event handlers for each field that needs to accept scanned in data. For the DIN field, adjust the value using:
var field = this.getField("DINField");
field.value = field.value.replace(/^~=(.+)..$/, '$1');
The code above assumes the field is named DINField. Change as appropriate. It is important to use logic like a RegExp for modifying the value because the on-blur event can fire multiple times per field. The code above will only remove the ~= app-id and last two characters once.
Likewise, for the product-id, set on "On Blur" handler to:
var field = this.getField("ProductField");
field.value = field.value.replace(/^~=<(.+)$/, '$1');
The code above assumes the field is named ProductField. This reg-ex only removes the app-id (and not the last two characters).
I need to detect a change in a Gravity Form field (form 5, field 215; is a number field), round the number so I can get a trailing zero if it doesn't already have one, and then return the new, rounded value back to the field. I tried to piecemeal something together using bits of other code I found, but I must be doing something wrong. I'm an absolute rookie with JavaScript.
I'm using Gravity Wiz's "Gravity Forms Custom JavaScript" plugin to insert this script only on the page with the appropriate form.
jQuery(“#gform_fields_215”).on(“change”,”#input_215″, ( function(e) {
var number = document.getElementById("input_215");
var rounded = number.toFixed(2);
document.getElementById("input_215").value = rounded;
}
What am I doing wrong? Probably everything! LOL
I know you have already forgotten you ever asked this. but here's the solution.
jQuery('#gform_fields_215').on('change','#input_215', ( function(e) {
var number = document.getElementById("input_3_1_5").value;
var rounded = parseInt(number).toFixed(2);
document.getElementById("input_215").value = rounded;
}
You have used jQuery and vanilla js syntax. if you would use only jQuery it would be done as below.
jQuery("#gform_3").on("change", "#input_3_1_5", function (e) {
$(this).val(parseInt(this.value).toFixed(2));
});
element value is a string it need to be parsed into a number before adding decimal places
this.value can be used to get value of current element
I have an input box in a component. I want to prevent the user from being able to add any input if the value of the input box contains more than 2 decimal places.
E.g. if a user inputs 10.95 I dont want to allow them write anything else after this value. They could still update it to 101.95 but it should prevent any input being added after the final decimal place.
The code I have so far is below.
class inputBox extends Component {
countDecimals(value) {
if(Math.floor(value) === value) return 0;
return value.toString().split(".")[1].length || 0;
}
updateValue(e) {
if(this.countDecimals(e.target.value) > 2) {
//prevent user from inputting into box after the decimal place...
}
}
render() {
return(
<input type='text' onChange={this.updateValue} />
)
}
}
You could use React controlled component and bind a state to the input's value atrribute. Then your onChange event handler will look like.
updateValue(e) {
this.setState({ value: e.target.value.toString().split(".").map((el,i)=>i?el.split("").slice(0,2).join(""):el).join(".")})
}
Worked for me.
document.getElementById("yourinput").oninput=function(){
this.value=this.value.toString().split(".").map((el,i)=>i?el.split("").slice(0,2).join(""):el).join(".");
};
Replace the value with a new value, that is shortened to two chars after each dot.
http://jsbin.com/soretokuse/1/edit
I think you need to save the oldvalue, that should work.
var input=document.getElementById('input'),
countDecimals=function(value) {
if(Math.floor(value) === value) return 0;
if(value.toString().split(".")[1])
return value.toString().split(".")[1].length || 0;
},
updateValue=function(val) {
if(countDecimals(val) > 2) {
input.value=input.getAttribute('oldValue');
}
};
input.oninput=function(){
updateValue(this.value);
input.setAttribute('oldValue',this.value);
}
<input id="input" type="text"/>
As far as my knowledge in Javascript and HTML goes there is no 'easy solution' for this. Working with both 'raw' JS and ExtJs forms has learned me that there are multiple ways to focus and manipulate a field. Which makes it hard to manipulate the inner value at the right time.
So allow me to split your issue in to multiple problems. Which I will attempt to tackle:
Triggering
You want your logic to run at all the times something happens to the field.
The following link provides you with the options:
http://www.w3schools.com/TAGS/ref_eventattributes.asp
When you use onchange it will trigger when someone changes the values after you blur the field (you click or tab away from the field). So that's no good.
You could try the key (up, down, press) events. But that excludes when you paste a value.
Long story short, you could in theory try to implement a function on every event you could think of to make sure you catch the users input and do what you want with it.
My solution is, start a timer when you focus a field and validate the value and do further logic. And finalize everything you wanted to do on blur.
Determining the correctness of the value
You could write some nifty regex or a single line statement that tells you if the value is correct. It's all the same in the end, it should fit your needs.
So something like:
var inputVar = element.value;
var inputFloat = parseFloat(inputVar);
var normalizeInput = Math.round(inputFloat * 100) / 100;
if(inputFloat > 0 && normalizeInput == inputFloat){
#correct value
}else{
#incorrect value
}
Handling correct/incorrect input
Now you want to handle the user input and do something.
Things like setting the field to disabled or read only would prevent further input and changes, but would not let your users do anything to your field.
As what I read is you want the field to not change in function, you want to be able to edit it.
So that leaves you with 2 options:
Editing the field content directly by overriding the element.value with the desired value.
Manipulating key inputs / selection to try and keep the cursor at same position the user left it while correcting the false input.
I would opt for the former as it is a lot less of a hassle, although it might mess with the cursor position (browser dependant).
Final implementation
So what I propose combining all the above:
On focus you start running a setTimeout or setInterval
http://www.w3schools.com/jsref/met_win_settimeout.asp
http://www.w3schools.com/jsref/met_win_setinterval.asp
In the function run then, you check if there is a previous value set.
The first time it is NOT so:
You have to hold this previous value somewhere, you could hold it in a variable within javascript or put it in to the field in the DOM.
http://www.w3schools.com/jsref/met_element_setattribute.asp
var inputElement.setAttribute('old_value', oldValue);
Now you check if this value is correct before saving it, else just default it back to blank (or attempt to normalise the value to something that validates, you could keep cutting away characters at the right for example).
Now on each run you check if the value is correct. If the value is correct, you hold the new value as the 'new' previous value (and calling setTimeout again if you use that method).
If it is not correct you write back the old value or attempt to normalise the input value and if that fails use the last correct value.
On the blur event you clear the setTimeout or setInterval running in the background:
http://www.w3schools.com/jsref/met_win_cleartimeout.asp
http://www.w3schools.com/jsref/met_win_clearinterval.asp
(Alternatively you could check if the document.activeElement is the same as the one that is run on this 'loop' so it knows when to stop).
On blur you check the value one last time and do the same logic to prevent false input.
PLAN B
Use the HTML5 number input field:
HTML 5 input type="number" element for floating point numbers on Chrome
Try <input type="number" step="0.01" /> if you are targeting 2 decimal
places :-).
edited Apr 27 '15 at 18:10
Andre Figueiredo
Which only works on browsers that support it.
i'm trying to live edit a text box value so that the result will be split every two character,
adding a column and starting from some default character.
what i have till now is this code, that obviously doesn't work:
$('#textboxtext').keyup(function (){
var text = $("#textboxtext").val();
//$(text).attr('maxlength', '12');
var splitted = text.match(/.{2}|.{1,2}/g);
var result = ("B8:27:EB:" + splitted.join(':'));
});
i need the live split and the default character inside the textbox but i really don't know where to start...
From your code, it seems like you're trying to create a text box that has some very specific behavior. It looks like it needs to format its value in such a way that it always begins with certain 'prefix' of B8:27:EB:, and every subsequent pair of characters is is separated by a :. This is actually a very complex behavior and you have to consider a number of different interactions (e.g. what happens when the user attempts to delete or modify the prefix). I usually try to avoid such complex controls if possible, however here is a quick implementation:
$('#textboxtext').keyup(function (e){
var prefix = "B8:27:EB:",
text = $(this).val(),
splitted, result;
if (text.indexOf(prefix) == 0)
text = text.substr(9);
else if (prefix.indexOf(text) == 0)
text = "";
text = text.replace(/:/g, '');
splitted = text.match(/.{1,2}/g) || [];
result = prefix + splitted.join(':');
$(this).val(result);
});
Demonstration
Type inside the text box and see what happens. Also note, there are all kinds of interaction that this implementation doesn't account for (e.g. right-clicking and pasting into the text box), but it's a start.