I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>
I want to create a javascript code to formatting my input number. For example when user type : 100000 it will convert automatically to 100,000 and if user type 1000.22 it will result 1,000.22. I have create code like this:
$(document).ready(function(){
$('input.angka').on("keyup click", function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="angka form-control" name="hargak" onkeyup="tots();" />
So all my input textbox which has class 'angka' will be converted. It works if I type it without decimals (10000, 20000, etc). But when I use decimal, these code gone wrong (1000.22 will result 1,000,.22) anyone can fix this code?
One possibility...
You should also accept navigating with arrows left and right...
$(document).ready(function(){
$('input.angka').on("keyup click", function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val();
var decs = num.split(".");
num = decs[0];
num = num.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRogueChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
if(decs.length > 1) {
num2 += '.' + decs[1];
}
$this.val(num2);
});
});
function RemoveRogueChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="angka form-control" name="hargak" onkeyup="tots();" />
I want to have a thousand separator (e.g. 1,000,000) in my Input field. However, it has to be of type number because I need to be able to adjust its value using "step". Code:
<input type="number" id='myNumber' value="40,000" step='100'>
I tried using Javascript to adjust the value but didn't work. Any help would be appreciated. Thanks!
Using autoNumeric plugin you can made a field as numeric input with different separators.
Include plugin:
<script src="~/Scripts/autoNumeric/autoNumeric.min.js" type="text/javascript"></script>
Html:
<input type="text" id="DEMO" data-a-sign="" data-a-dec="," data-a-sep="." class="form-control">
Script:
<script>
jQuery(function($) {
$('#DEMO').autoNumeric('init');
});
</script>
You can type only number, if you input 100000,99 you will see 100.000,99.
More: https://github.com/autoNumeric/autoNumeric
Check this webdesign.tutsplus.com tutorial
Final result is summarized here (look at direct Codepen playground)
$("#formInput".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) {
return;
}
var $this = $(this);
// Get the value.
var input = $this.val();
input = input.replace(/[\D\s\._\-]+/g, "");
input = input?parseInt(input, 10):0;
$this.val(function () {
return (input === 0)?"":input.toLocaleString("en-US");
});
});
Notes:
toLocaleString() javascript function Actually show thousands separator (example and doc)
run below code in your console to get the idea
(30000000).toLocaleString('en-US',{useGrouping:true})
You can fake this functionality by using a pseudo-element to display the comma version.
div[comma-value]{
position:relative;
}
div[comma-value]:before{
content: attr(comma-value);
position:absolute;
left:0;
}
div[comma-value] input{
color:#fff;
}
A wrapping div is required because inputs can't have pseudo elements.
<div>
<input type="number" id='myNumber' value="40000" step='100'>
</div>
And a little bit of JavaScript to insert commas every third character
myNumber.value = commify(myNumber.value)
myNumber.addEventListener("change", function(){
commify(event.target.value)
})
function commify(value){
var chars = value.split("").reverse()
var withCommas = []
for(var i = 1; i <= chars.length; i++ ){
withCommas.push(chars[i-1])
if(i%3==0 && i != chars.length ){
withCommas.push(",")
}
}
var val = withCommas.reverse().join("")
myNumber.parentNode.setAttribute("comma-value",val)
}
Check out the fiddle
Create a mask input displaying the formatted number. This solution avoids changing the type or the value of the input.
$("input.mask").each((i,ele)=>{
let clone=$(ele).clone(false)
clone.attr("type","text")
let ele1=$(ele)
clone.val(Number(ele1.val()).toLocaleString("en"))
$(ele).after(clone)
$(ele).hide()
clone.mouseenter(()=>{
ele1.show()
clone.hide()
})
setInterval(()=>{
let newv=Number(ele1.val()).toLocaleString("en")
if(clone.val()!=newv){
clone.val(newv)
}
},10)
$(ele).mouseleave(()=>{
$(clone).show()
$(ele1).hide()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="mask" type="number" value="12345.678"/>
csq recommends using the jQuery autoNumeric plugin. I found it to be very easy and intuitive to use.
My only gripe is that it forces <input type="text"> rather than <input type="number">. This means you lose the funcionality of step, but you gain users of your site being able to use commas in fields.
I guess you could use expected values of less than 1,000 as <input type="number"> and values more than 1,000 as <input type="text">
I've managed to pull it off after modifying https://stackoverflow.com/a/70726755/4829915 because:
The code didn't actually add commas due to not using Number().
It deleted the entire field when the initial value was blank.
No demo was provided.
Not saying the original approach was wrong or not, but I chose to use onfocus and onblur directly on the input itself.
Therefore, here's a revised answer:
Start with <input type="text">. You can still add min, max and step properties.
Add onfocus and onblur handlers to the <input> node:
function use_number(node) {
var empty_val = false;
const value = node.value;
if (node.value == '')
empty_val = true;
node.type = 'number';
if (!empty_val)
node.value = Number(value.replace(/,/g, '')); // or equivalent per locale
}
function use_text(node) {
var empty_val = false;
const value = Number(node.value);
if (node.value == '')
empty_val = true;
node.type = 'text';
if (!empty_val)
node.value = value.toLocaleString('en'); // or other formatting
}
<input type="text" min=0 onfocus="use_number(this)" onblur="use_text(this)">
function addCommas(nStr) { ....
In addition of yovanny's answer I create a Vue component which use this function.
Vue.component("in-n", {
template:
`<input #keyup="keyup" #keypress="isNumber($event)" v-model="text" type="text" />`,
props: ["value"],
data() {
return {
text: ""
}
},
methods: {
addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
isNumber: function (evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
evt.preventDefault();;
} else {
return true;
}
},
keyup() {
this.text = this.addCommas(this.text.replace(/,/g, ''));
this.$emit("input", parseInt(this.text.replace(/,/g, '')))
}
}
})
I found a much simpler answer:
Start with <input type="text">. You can still add min, max and step properties.
Add onfocus and onblur handlers to the <input> node:
node.addEventListener('onfocus', () => {
const value = node.value;
node.type = 'number';
node.value = Number(value.replace(/,/g, '')); // or equivalent per locale
});
node.addEventListener('onblur', () => {
const value = node.value;
node.type = 'text';
node.value = value.toLocaleString(); // or other formatting
});
When the user selects the input, it will convert to a regular numeric input with thousands separators removed, but with a normal spinner. When the user blurs the input, it reverts to formatted text.
I add an onkeyup handler that blurs the input when the "enter" key is pressed.
I have updated #CollenZhou answer https://stackoverflow.com/a/67295023/6777672 as on mouse leave, input looses focus which is annoying. I have also added all input type numbers to selector as well as class.
$('input.thousands-separator, input[type="number"]').each((i,ele)=>{
let clone=$(ele).clone(false)
clone.attr('type','text')
let ele1=$(ele)
clone.val(Number(ele1.val()).toLocaleString('en'))
$(ele).after(clone)
$(ele).hide()
clone.mouseenter(()=>{
ele1.show()
clone.hide()
})
setInterval(()=>{
let newv=Number(ele1.val()).toLocaleString('en')
if(clone.val()!=newv){
clone.val(newv)
}
},10)
$(ele).mouseleave((event)=>{
if ($(ele).is(':focus')) {
event.preventDefault();
} else {
$(clone).show()
$(ele1).hide()
}
})
$(ele).focusout(()=>{
$(clone).show()
$(ele1).hide()
})
})
try
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
I am trying to add a percentage to a value (number) that is in an input field.
is this possible using javascript?
this is what i came up with but it doesn't do anything.
<script language="javascript">
function multiply() {
var ans = (document.form.myNumber.value) + ("3.5%"),
total = Math.round(ans*100)/100;
document.form.sum_total.value = total;
}
</script>
please let me know if this question is not suitable for this website and i will delete it.
Thanks
EDIT:
So far i have tried everything and nothing seem to work for me.
here is what I have done so far:
JAVASCRIPT:
<script type="text/javascript">
$("#myNumber").keyup(function(){
$("#sum_total").val($(this).val());
});
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script language="javascript">
function multiply() {
var ans = parseFloat(document.form.sum_total.value);
ans = (ans * 0.035) + ans
}
</script>
HTML:
<form>
<input type="text"id="myNumber" name="myNumber" value="" onkeyup="multiply()" onkeypress="return isNumberKey(event)" ><br /><br />
<input type="text" id="sum_total" readonly="true" name="sum_total" value="">
<input name="perc" id="perc" type="hidden" value="3.5%" />
</form>
Basic math applies here. 3.5% is actual 0.035, so parse you input value:
var ans = parseFloat(document.form.myNumber.value);
Do the math
ans = (ans * 0.035) + ans
Or multiply by 103.5%
ans *= 1.035
I've a user registration form and I want to show the password rules in small tool tip along with the validation message like invalid password or valid password.My password rule is it contains 7 letters, 1 digit and 1 upper case letter etc.
Currently I've both of these but showing it in two different tool tip how can I merge two and show it in a single one.
<html>
<head>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
<title>Test</title>
</head>
<script>
function validatePassword(obj) {
//rule contains 7 chars and upper case and lower case and digit
var password = obj.value;
var numLowers = 0;
var numCaps = 0;
var numDigits = 0;
var valid = true;
if(password.length > 7) {
for(i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if(charCode >= 48 && charCode <= 58 )
numDigits++;
else if(charCode >= 65 && charCode <= 90 )
numCaps++;
else if(charCode >= 97 && charCode <= 122 )
numLowers++;
}
if(numDigits < 1 || numCaps < 1 )
valid = false;
}
else {
valid = false;
}
if(!valid){
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
}
</script>
<body>
<div>
<form id="test" action ="#">
<div id="password-container">
<input type="text" id= "password" name="password" size="30" onKeyUp="validatePassword(this)" title=" Password contains 7 -20characters <br/> and upper case and digits." />
</div>
<div id="password-error" class="error" style="display:none;">Invalid Password</div>
</form>
</div>
</body>
</html>
$("#test :input").tooltip({
// place tooltip on the right edge
position: "center right",
// a little tweaking of the position
offset: [-2, 10],
// use the built-in fadeIn/fadeOut effect
effect: "fade",
// custom opacity setting
opacity: 0.7
});
You can see a working example here
http://jsfiddle.net/ddrYp/6/
Here's a solution, you won't need to use both the tooltip and password error div.
http://jsfiddle.net/ddrYp/12/
But you may run into problems with this in the future because the tooltips are not uniquely identified. I'm not familiar with the plugin, but if you could add an individual ID to each tooltip, that's fix it for you. Once you do that, you could reference the tooltips by using their ID instead of $(".tooltip")... if you expand this to have multiple inputs when you do $(".tooltip").append(/*something*/) or $(".tooltip").HTML(/*something*/) you're going to modify every tooltip.. which may not matter, because only one is visible at a time... but it's still an inefficiency issue and a bit of a bug
Here's the example of the ebay password verification example that you were looking for:
http://jsfiddle.net/cFrpz/7/
Try this http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Here you go :
<html>
<head>
<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>
<title>Test</title>
</head>
<script>
function validatePassword(obj) {
//rule contains 7 chars and upper case and lower case and digit
var password = obj.value;
var numLowers = 0;
var numCaps = 0;
var numDigits = 0;
var valid = true;
if(password.length > 7) {
for(i = 0; i < password.length; i++) {
var charCode = password.charCodeAt(i);
if(charCode >= 48 && charCode <= 58 )
numDigits++;
else if(charCode >= 65 && charCode <= 90 )
numCaps++;
else if(charCode >= 97 && charCode <= 122 )
numLowers++;
}
if(numDigits < 1 || numCaps < 1 )
valid = false;
}
else {
valid = false;
}
if(!valid){
$(".tooltip").append($("#password-error"));
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
}
</script>
<body>
<div>
<form id="test" action ="#">
<div id="password-container">
<input type="text" id= "password" name="password" size="30" onKeyUp="validatePassword(this)" title=" Password contains 7 -20characters <br/> and upper case and digits." />
</div>
<div id="password-error" class="error" style="display:none;">Invalid Password</div>
</form>
</div>
</body>
http://jsfiddle.net/ddrYp/9/
I haven't tested this but it should be fine. From your working example, replace this:
if(!valid){
document.getElementById("password-error").style.display="block";
}
else {
document.getElementById("password-error").style.display="none";
}
with this:
$tooltip = $(".tooltip");
if(!valid && $tooltip.find("div.error").length < 1){
$tooltip.append("<div class='error'>"+$("#password-error").html()+"</div>");
}
else if(valid) {
$tooltip.find(".error").remove();
}