How to create prevent default function for input? - javascript

When a user enters numeric values I just want to display even number I want to set prevent default on odd values.
HTML:
Enter any number: <input type="text">
<p id="even"></p>
JavaScript:
function (e) {
e.preventDefault();
}

You can add an event listener to the input element and validate that the number is even.
DEMO
JavaScript
var num = document.getElementById('num');
var out = document.getElementById('out');
var isNumber = function(n) { return n == parseFloat(n); }
var isEven = function(n) { return isNumber(n) && (n % 2 == 0); }
var isOdd = function(n) { return isNumber(n) && (Math.abs(n) % 2 == 1); }
var myFunction = function(e) {
var val = num.value;
if (isEven(val)) {
out.innerHTML = val;
} else {
e.preventDefault();
}
};
num.addEventListener('blur', myFunction, false);
HTML
Enter any number: <input type="text" id="num" />
<hr />
Value: <span id="out"></span>
Update
If you want live validation, change blur to keyup.
num.addEventListener('keyup', myFunction, false);

If you are asking how to detect an odd value, you could use something like
function whatever(e){
if(value % 2 != 0){
e.preventDefault()
}else{
//Do something
}
}

Probably something like this:
$("input").mouseup(function() {
var num = $(this).val();
if (num % 2) {
console.log(num);
}
});
EDIT: and here it is in plain JS:
var el = document.getElementsByTagName("input")[0];
el.onkeyup = function () {
var num = el.value;
if (num % 2 == false) {
console.log(num);
}
};

Related

html Input type number with Thousand Separator

i want to add thousand separator on keyup event in input type number
but this work just in 6 character, if more than 6 character, value on input has reseted
this my short code
<input type="number" id="tanpa-rupiah" step="any">
var dengan_rupiah = document.getElementById('dengan-rupiah');
dengan_rupiah.addEventListener('keyup', function(e)
{
dengan_rupiah.value = formatRupiah(this.value, 'Rp. ');
});
function formatRupiah(bilangan, prefix)
{
var number_string = bilangan.replace(/[^,\d]/g, '').toString(),
split = number_string.split(','),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{1,3}/gi);
if (ribuan) {
separator = sisa ? '.' : '';
rupiah += separator + ribuan.join('.');
}
rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
this my fiddle https://jsfiddle.net/C2heg/4619/
This might suit you. On keydown prevent the default action if it is not a number key. On keyup, parse the value and update it. Use the data- attributes to store and get the original value.
var elem = document.getElementById("num");
elem.addEventListener("keydown",function(event){
var key = event.which;
if((key<48 || key>57) && key != 8) event.preventDefault();
});
elem.addEventListener("keyup",function(event){
var value = this.value.replace(/,/g,"");
this.dataset.currentValue=parseInt(value);
var caret = value.length-1;
while((caret-3)>-1)
{
caret -= 3;
value = value.split('');
value.splice(caret+1,0,",");
value = value.join('');
}
this.value = value;
});
function showValue()
{
console.log(document.getElementById("num").dataset.currentValue);
}
<input type="text" id="num" maxlength="30">
<button onclick="showValue()">Get Value</button>
Ok I have posted answer below. I have added limit of 20 numbers. You can change it as per your need.
You can use Number.toLocaleString() for this purpose.
Below is working example:
// When ready.
$(function() {
var extra = 0;
var $input = $("#amount");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = $(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="amount" name="amount" type="text" maxlength="20" />
change your the input type equal to "text" then its work
<input type="text" id="tanpa-rupiah" step="any">
checkout jsfiddle

Textbox allow only decimal numbers with dot using jquery

I have one textbox.It should be allow only decimal numbers and after dot only allow two digit(example 34545.43). how we can do it using jquery i have searched in google and stackoverflow but not satisfied answer because some script is not working in chrome and firefox. I tried but it is not working properly.So need help how to do it.http://jsfiddle.net/S9G8C/1685/
Js:
$('.allow_decimal').keyup(function (evt) {
var self = $(this);
self.val(self.val().replace(/[^0-9\.]/g, ''));
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
evt.preventDefault();
}
});
This jQuery function will round the value on blur event of textbox
$.fn.getNum = function() {
var val = $.trim($(this).val());
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
var num = parseFloat(val);
var num = num.toFixed(2);
if(isNaN(num)) {
num = '';
}
return num;
}
$(function() { //This function will work on onblur event
$('#txt').blur(function() {
$(this).val($(this).getNum());
});
});
Number: <input type="text" id="txt" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can directly remove the 3rd digit when the user enters that.
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
<input id="txtId" type="text"></input>

Incorrect return value javascript

I am trying to create a simple guessing game and my return value or my functionality seems correct. I have console.logged typeof for my input value as well as my randNum value and they are both numbers. However my alert is always incorrect. What am I doing wrong?
var currentGuess = false;
var randNum = Math.floor(Math.random() * 100)
var input = document.getElementById("guess").value;
var input = parseInt(input);
var btn = document.getElementById("submit");
var results = document.getElementById("results");
console.log(randNum);
function check() {
checkNum(input, randNum);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
function checkNum(guess, actualNum) {
currentGuess = false;
if(guess === actualNum) {
return true;
}
return currentGuess;
}
btn.addEventListener("click", check, false);
You didn't take input again when check is called.
just add this in your check function
input = parseInt(document.getElementById("guess").value);
Like this
function check() {
input = parseInt(document.getElementById("guess").value);
checkNum(input, randNum);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
Fiddle with working solution: https://jsfiddle.net/pp9Lrpe6/
You are listening for the click even on the input, but getting the input value when everything is loaded, which is empty - returning input = NaN. This value isn't updated when a user clicks:
var randNum, btn, results;
// Generate random number.
randNum = Math.floor( Math.random() * 100 );
// Submit button to listen for click events on.
btn = document.getElementById( 'submit' );
// Display result one at a time in #results.
results = document.getElementById( 'results' );
// Number to guess.
console.log( 'Random number: ' + randNum );
// Check the input on click of #submit
function check() {
var input = parseInt( document.getElementById( 'guess' ).value, 10 );
if ( input === randNum ) {
results.innerHTML = '<p class="correct">' + input + ' is correct!</p>';
} else {
results.innerHTML = '<p class="incorrect">' + input + ' is not correct!</p>';
}
}
// Add event listener for #submit
btn.addEventListener( 'click', check, false );
As a good practice, you should give you input the type="number".
You should also declare the radix for parseInt (MDN)
try this:
<html>
<head>
</head>
<body>
<input type="text" id="guess"><br>
<input type="button" id="submit" value="check"><br>
<div id="results"></div>
<script>
var currentGuess = false;
var randNum = Math.floor(Math.random() * 100)
var btn = document.getElementById("submit");
var results = document.getElementById("results");
console.log(randNum);
function check() {
var input = document.getElementById("guess").value;
var input = parseInt(input);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
btn.addEventListener("click", check, false);
</script>
</body>

input field: limit the number of letters and numbers typed

Is there a way to limit the number of letters and numbers allowed to type in to an input field? I would like to only allow 3 letters and 2 numbers to be typed in, in whatever order.
Is this possible using the jQuery Mask Plugin? Or not?
See my jsFiddle here: http://jsfiddle.net/0akoL2x2/
html:
<input type="text" class="preview" size="30" placeholder="Preview text" class="text-input" maxlength="5" autofocus />
jquery:
jQuery('.personalisation').mask("XXXZZ", {
translation: {
'X': {pattern: /[A-Za-z0-9]/},
'Z': {pattern: /[A-Za-z0-9]/},
}
How about using a data attribute? Let's call it data-temp:
<input type="text" class="alnum" maxlength="5" data-temp="">
Use $(document).on('input'... to monitor all changes (even dynamic elements), and revert back immediately if the new value exceeds the maximum. Otherwise, let it happen, and update data-temp to this new value.
$(document).on('input', '.alnum', function(){
var txt = $(this).val();
if(
txt.replace(/[^0-9]/g,"").length > 2 ||
txt.replace(/[^A-Za-z]/g,"").length > 3 ||
txt.replace(/[a-zA-Z0-9]/g,"").length != 0
){
$(this).val( $(this).data('temp') );
return;
}
$(this).data('temp', txt);
});
JSFiddle demo
Here is a fiddle that works:
http://jsfiddle.net/igorshmigor/k2ss62gg/3/
The JS code looks like this:
var numberCountLimit = 2;
var letterCountLimit = 3;
$(document).ready(function() {
$('.preview').keypress(function(key) {
if (key.charCode == 0){
return true;
}
var current = $(this).val();
var filtered = current.replace(/[^a-z0-9]/gmi,'');
$(this).val(filtered);
var digits = filtered.replace(/[^0-9]/gmi,'');
var alpha = filtered.replace(/[^a-z]/gmi,'');
var digitCount = digits.length;
var alphaCount = alpha.length;
var isNumber = false;
var isAlpha = false;
if (key.charCode > 47 && key.charCode < 58){
isNumber = true;
if (digitCount >= numberCountLimit){
return false; // too many digits
}
}
if (key.charCode > 64 && key.charCode < 123){
isAlpha = true;
if (alphaCount >= letterCountLimit){
return false; // too many letters
}
}
if (!isAlpha && !isNumber){
return false;
}
});
});
P.S.: I don't think this can be done with just the jQuery Mask Plugin.
Give your text box an ID.
$("#box").mask('XXXZZ', {'translation': {
X: {pattern: /[A-Za-z0-9]/},
Z: {pattern: /[A-Za-z0-9]/}
}
});
JSFiddle
How about this, you hook the keypress and check the number/letter counters and if it exceeds you will just ignore the keypress (by returning false)
var numberCount = 0;
var numberCountLimit = 2;
var letterCount = 0;
var letterCountLimit = 3;
$(document).ready(function() {
$('.personalisation').keypress(function(key) {
var currentText = $(this).val();
numberCount = 0;
letterCount = 0;
for (var i = 0, len = currentText.length; i < len; i++) {
if(currentText.charCodeAt(i) < 48 || currentText.charCodeAt(i) > 57) {
//Is number
if((numberCount+1) > numberCountLimit) {
return false;
}
numberCount++;
} else {
//Is letter
if((letterCount+1) > letterCountLimit) {
return false;
}
letterCount++;
}
}
return true;
});
}

more than currency input field

I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?

Categories

Resources