Paste Only Numbers in Input Field [duplicate] - javascript

This question already has answers here:
Putting text in a number input doesn't trigger change event?
(3 answers)
Closed 5 years ago.
I have an Input field in my form. I want to be able to past only numbers in this input field.
For example: (Some random characters on my clipboard W123W000)
Should Paste = 123000
Note: Only works in Chrome Browser
I have been searching online and so far I came up with this but it's not working properly.
var inputBox = document.getElementsByClassName('numbersOnly');
inputBox.onchange = function () {
inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
}
<input id="number" type="number" class="numbersOnly">

Use jQuery for cross-browser compatibility and bind the event input to handle every change.
Firefox: <input type="number">
elements automatically invalidate any entry that isn't a number (or empty, unless required is specified).
You can change to type=text, but you will lose the numeric keyboard behavior in devices.
var inputBox = $('.numbersOnly').on('input', function(e) {
e.preventDefault();
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="number" type="text" class="numbersOnly">

Related

Sort string based on user input using JavaScript [duplicate]

This question already has answers here:
Sort a string alphabetically using a function
(3 answers)
Change input value onclick button - pure javascript or jQuery
(6 answers)
change value of input field onclick
(5 answers)
Closed 3 months ago.
The question is how to sort the letter in alphabetic order based on the input in a HTML input tag, then clicks a button to sort it, after click the button the input will move to a text area and is already sorted when button is click, so that button need to have the insert function and sorting function, now the input can be insert to the textarea but not sorted, thanks.
Example of input:
andwe
output:
adenw
i want to define my input as an element, and write onclick="sortstring(element of my input)" in button, but i dont know how to define and dont have a sort function yet.
function sortString() {
const inputElement = document.getElementById('input');
const sortResult = inputElement.value.split('').sort().join('');
inputElement.value = sortResult;
}
<input id='input' type="text" value=''/>
<button onclick="sortString()">sort</button>
function sortString(str) {
document.querySelector('#result').innerHTML = str.split('').sort().join('')
}
<input type='text' onkeyup='sortString(this.value)'>
<p id="result"></p>

Get new value from one input to another [duplicate]

This question already has answers here:
How to Copy Value from one Input Field to Another
(2 answers)
Closed 2 years ago.
Let's say I have two inputs in HTML:
<input type="number" id="test1">
<input type="number" id="test2">
Now I've an algorithm which should be called after enter of some number in input. For example, if I enter 10 in first input, in twice input must be returned 5 (10/2) without click of any button. So how to archive that?
You can use the input event listener.
document.getElementById("test1").addEventListener("input", function() {
document.getElementById("test2").value = this.value/2;
})

Check if input field has focus and pass input variable to function [duplicate]

This question already has answers here:
Using jQuery to test if an input has focus
(15 answers)
Closed 7 years ago.
I have an input field which will be updated every x seconds:
<input type="number" name="METER" id="METER.NUM" min="0" max="500" step="0.10" oninput="setMeter(currentValue);" >
Now, I want to check if the input field has focus (user clicked into the field).
If the field has focus:
I will stop updating the field and the user can put some value into the field
Then the value should be passed to a function
This is the javascript code:
if (document.getElementById(array[0]).name == "METER") {
// check if the input field has focus
// stop updating
}
What's wrong with my approch/code? I think one problem is, that the function call by oninput doesn't work. But it works by onClick.
use onfocus = myFunction()
function setMeter() {
console.log('hey, im focused');
// do stuff here
}
<input type="number" name="METER" id="METER.NUM" min="0" max="500" step="0.10" onfocus="setMeter();" >

Replace an input with another dynamically created input [duplicate]

This question already has answers here:
change type of input field with jQuery
(29 answers)
Closed 8 years ago.
I want to replace an existing file input field entirely with a text input field, with all properties intact like id, name, etc. How do I do that using jQuery?
Prelude:
I have an <input type="file" name=".." id=".." /> that I am using for AJAX based uploads. (yes, For IE, I am submitting the form using IFRAMEs.)
When the upload is done, I go into my success callback function, where I am trying to change the original <input type="file" to <input type="text".
In other browsers, this is working fine when I simply run the following code:
$originalInput[0].type = 'text';
$originalInput[0].value = 'response code';
But this is not working in IE, where I came to know from SO that it is a security concern and hence not allowed. I want to write minimum code for this.
From user2259571's answer, I did this following in a shorter one-line way:
$originalInput
.replaceWith( $originalInput[0].outerHTML.replace(/type="file"/, 'type="input"') );
IE does not allow this, but a workaround can be:
$('body').find('input:file').each(function() {
$("<input type='text' />").attr({value: 'response code' }).insertBefore(this);
}).remove();
possible duplicate of jQuery change input type
I think you can reach this very simple by placing two inputs,
<input type="file" name="somename1" id="someid1"/>
<input type="text" name="somename1-after" id="someid1-after" style="display:none"/>
In you request callback you can remove the type="file" input field, strip the "-after"
suffix and show the type="text" input field.
Long live jQuery
var fileInput = $('input[type="file"]');
var textInput = $('<input type="text"/>');
//can copy properties here
textInput.value = 'response code';
textInput.className = fileInput.className;
textInput.insertBefore(fileInput);
textInput.remove();
var input = $("input[type=file]");
var inputHTML = input.clone().wrapAll("<div>").parent().html();
var newinputHTML = inputHTML.replace(/type="file"/, 'type="text"');
input.replaceWith(newinputHTML);
http://jsfiddle.net/QdZDb/1/

Get value of <input type="number"> with JS when it contains non-numeric characters

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.

Categories