I want to exclude all characters which are not a digit or minus.
What strikes me is that I cannot start with a minus or enter it anywhere. Only after digits and using the keyboard arrow button is entering a minus possible.
What I would like is being able to just enter -60 or something the like.
What should I change?
$('.minus').keyup(function() {
var txt = $(this).val();
var nwtxt = txt.replace(/[^\d-]/ig, "");
$(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus">
Instead of using input type number use text
I think it's some kind of browser defence meganism that whenever you insert something that is not a number inside a number input field and you request the value from it, it will simply be null/undefined. On type="text" it looks like this is fine.
Also note your cursor is always put at the end of the text, because you replace the text always. So you can't insert a - (dash) before a number with only keyboard interaction. and a dash anywhere but in front of a number is invalid!
You can try to type in -60 in the number field as well but you first need to insert. 60 and then the minus character.
also its better to use $('.minus').input( instead of keyUp, since you can use the mouse to insert values as well (and the scroll wheel).
$('.minus').keyup(function() {
var txt = $(this).val();
console.log("value i got:",txt); //i added this logging to see that you didn't get anything on number.
var nwtxt = txt.replace(/[^\d-]/ig, "");
if(nwtext !==txt) //add this if statement so your cursor does not constantly jump to the end!
$(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus" placeholder="number">
<input type="text" maxlength="9" class="tekstvakjes minus" placeholder="text">
Related
I have a
<input id="TxtBox" runat="server" autocomplete="off" onkeypress="">
And while doing the keypress, directly with js code, it replaces all the characters for '*'. Like a password typing.
Edit: 2022
As i read this old question i found imprecision why i wanted to avoid type="password" at that time. It was because if that attribute were in the tag the browser would remind a old password and it was annoying.
Edit:
I passed all day trying do put the autocomplete=off on all of my inputs to the browser stop asking password while someone is filling a form on my site, ddnt worked(a tried a few more things). And i thought in this type of solution i tried the javascript replace function but it only returned one char and decided to ask about a complete sequence of '*' while writing in a input. Tks for all the help.
sorry if i wasnt clear in the context i was just thinking in the code. i thought in some old i did before in C language but anyway i asked.
Edit:
I asked help how to do this in JS i did some stuff on keypress with JS functions like replace i did some code but i simply erased it and asked for some help. Next time i will post code to have some kick start code. I was doing something like
onkeypress="this.value=this.replace(this.value,'*')"
Tks in advance.
This is for in a visible input see a password typing and in a hidden i have it.
note: i want to avoid type="password"
Why do you need JavaScript to accomplish what HTML gives your for free? The element exposes all the same attributes/properties so you can still use it like a text box.
<input type="password">
If you feel you must reinvent the wheel, this can be done by using two fields. The user will type in the first and it will display the mask character and the actual key will be stored in a hidden input field for processing:
// Get references to DOM elements:
var txt = document.getElementById("txtMask");
var hdn = document.getElementById("pass");
// This keeps track of how many characters should be displayed
var maskLen = 1;
// Set up input event on first box
txt.addEventListener("keydown", function(evt){
// Manually put the right amount of mask characters into the box
// and update the maskLen value
var str = '#'.repeat(maskLen++)
this.value = str;
// Cancel the event and stop bubbling
evt.preventDefault();
evt.stopPropagation();
// Set the actual typed data into the hidden field
hdn.value += evt.key;
// Just for testing:
console.clear();
console.log("Actual data is: " + hdn.value);
});
<input type="text" id="txtMask" autocomplete="false">
<input type="hidden" id="pass">
Use type="password"
Like this:
<input type="password" id="TxtBox" runat="server" autocomplete="off" onkeypress="">
You can also do one of these:
input { -webkit-text-security: none; }
input { -webkit-text-security: circle; }
input { -webkit-text-security: square; }
input { -webkit-text-security: disc; /* Default */ }
You can use those without having a type="password"
I need to send a form off to where a single hidden field is comprised of two of the other fields that will be dynamically populated by a user (post/zip code and first line of address) where after regular expression only the numbers remain "123|456".
I have attempted to start, using the code below, where I monitor the output in the console. I have managed to dynamically edit a textfield so that all that is shown are the numbers but this is not suitable for a user. So I was trying to store the edited textfield data into the hidden field whilst leaving the complete line of address but I could not see how this can be done.
Also, can someone explain why if I remove the commented line the variable is not stripped of any letters albeit just 1?
$(document).ready(function() {
$("#testMe").on('propertychange change click keyup input paste', function() //attaching multiple handlers
{
var removedText = $("#testMe").val().replace(/\D/, '');
$("#testMe").val(removedText); //only removes once if removed
console.log(removedText);
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="hidden" id="hide" value="">
<input type="text" id="testMe" value="">
<span id="test2"></span>
The question was kind of unclear to me, but I did my best to answer.
https://jsfiddle.net/ccu6j6xu/
<input type="hidden" id="hide" value="">
<input type="text" id="zip" value="">
<input type="text" id="address" value="">
<span id="test2"></span>
In the HTML, all I did was add another input, because I think that's what you wanted to do?
$(document).ready(function() {
$("#zip, #address").on('propertychange change click keyup input paste', function() {
var concatText = $("#zip").val().replace(/\D/g, '') + "|" + $("#address").val().replace(/\D/g, '');
$("#test2").text(concatText);
$("#hide").val(concatText);
});
});
Then in the JavaScript, I changed the selector to match the new inputs, and then I changed the function.
The first line of this function defines a variable concatText to hold the values of each input concatenated with a | character between. Each one has regex applied to remove the letters for the final value. Then the next line changes the value of the span to display, and the final line applies this value to the hidden input.
Again, the question was kind of confusing to me, but feel free to comment and I can help some more :)
EDIT: reread the question, I think this better answers
I want to code a currency converter, and only integer and float are allowed.So i detect the input change and do some calculation.
html snippet is as below:
<input type="number" id="currency">
JS is:
$("#currency").on("input", function(e){
var value = this.value
console.log(value)
});
Everything works well except when input is "12.", the value is an empty string?
what i want is 12 actually. How to solve the issue? Any help would be appreciated.
JSfiddle of snippet
This is because you are using input type="number"which wont allow any input other than number(including floating numbers).
But you put string or char as input you will see empty log statement and on doing parseInt(this.value) it will log NaN.
So if you still want to give string/number as a input you can use input type="text"
<input type="text" id="currency">
Input type="number" means any number including float, integer and does not allow to enter text.
so the best solution might be Input type="text" and if you want precision you can get by toFixed method as below example
$("#currency").on("input", function(e){
var value = this.value
if(isNumeric(value)){
alert(parseInt(value));
}
else{
alert("text")
}
});
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="currency">
Your issue is related to your localization.
As everybody confirms, <input type="number"> allows to enter integers and float.
So when typing 12., why do you get an empty result while some others get 12?
Because their decimal point is dot, while yours is something else!
E.g.: on my own system, where decimal point is comma, I get an empty result when typing 12. and 12 when typing 12,.
This is my problem. When I try to set the value of an input field in FireFox nothing happens. I don't get any errors. It simply just doesn't work. It is supposed to add two decimal places after the number. It works perfectly in Chrome. Here's my jQuery code...
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="$0.00" />
I've tried using $(this).attr('value' n); but that doesn't work either.
So, it does "work", but Firefox simply formats the number differently, it truncates the 0s. If you do
$(this).val(6.00);
you will see that it shows 6.
If you do
$(this).val(6.50);
it will show 6.5 but also an error that it is not a valid value.
What's with the error?
The default step value of the input is 1 which makes Firefox only consider numbers as valid that are a multiples of that.
If you set step="0.01" then Firefox considers floating point numbers as valid.
But the formatting is still incorrect
However, this still won't show the decimals for whole numbers. I guess that's just how it is given that the spec doesn't seem to describe how the value should be formatted.
If the format is more important to you than the functionality of the number input, use a normal text input instead.
This has to do with how firefox treats the number input type. https://bugzilla.mozilla.org/show_bug.cgi?id=1003896
You can try text if that is an acceptable input type for you.
Having found the above citation everything below is only interesting but not useful
For example in Firefox vs Chrome check out
http://jsbin.com/coyuyipeca/edit?html,js,output
You'll see the value is indeed formatted correctly in the alert in FF but lost when pushed to the number field. Change the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="text" placeholder="$0.00" />
and you'll see it work. Of course you will lose the benefits of the number field (notably mobile inputs) so it depends on how important that functionality is to you.
Note: One odd thing I note is if you set the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" step=".01" placeholder="$0.00" />
You can use the increment button and get decimals, it only seems to be lost when jQuery sets the value. Not sure if this is an issue with jQuery or with FF
This seems to work for me in the following jsfiddle:
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="0.00" />
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
Which is your exact code. The only thing is you cannot input '$' symbol into a number field. That would fail. So for eg: '3.4512' gets truncated to '3.45' and set properly, but '$3.4512' just gets cleared when I try it.
https://jsfiddle.net/bz0os3kp/1/
Your code seems to work. It does truncate the trailing zeros in firefox however.
I found a work around that seems to work in Firefox. I change the type of input to number on focus giving me the proper keypad on mobile but then change the type back to text on blur giving me to two decimal places. See the code below...
$('input.drawer').on('blur', function(){
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).attr('type','text');
$(this).val(n);
});
$('input.drawer').on('focus', function(){
$(this).attr('type','number');
});
This jsfiddle demonstrates the following issue.
The simplest example is:
<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);
This logs 1 as expected. THIS however:
<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);
Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.
This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.
It appears jQuery's .val() method gives the same result.
This is what I was looking for:
$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});
I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3
However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to #int32_t for the suggestion.
You're not supposed to use <input type=number> for things that are not numbers (in very mathematical senseāit won't work for phone numbers or zip codes either) and clearing of the value is deliberate.
You can test whether device supports type=number and attach your fallback only if it doesn't:
var input = document.createElement('input');
input.setAttribute('type','number');
if (input.type != 'number') { // JS property won't reflect DOM attribute
polyfill_number();
}
Alternatively (especially if your number is a zip code, serial number, etc.) you can use:
<input type=text pattern="[0-9]*">
and this will change the keyboard too.