If input field is empty fill it with random number - javascript

I want to fill all empty number fields with a random number. I can populate all fields with a random number as shown below.
$.each(numberField, function () {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
});
But if I try and wrap it around an
if (numberField.val() === "")
It doesn't work
What am I doing wrong here? see fiddle
<input type="number" value="0">
<input type="number" value="">
<input type="number" value="4">
<input type="number" value="5">
<input type="number" value="">
var numberField = $('input[type=number]');
var x = '';
if (numberField.val() === "") {
$.each(numberField, function () {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
});
}

You need to move your condition (you are looking if an array is equal to "", which is never the case). You also need to trim the value to check if it is really empty:
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if ($.trim($(this).val()) === "") {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
}
});

in your example numberField is an array so your code must be like this:
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if ($(this).val() === "") {
x = Math.floor((Math.random() * 10) + 1);
$(this).val(x);
}
});

See the updated fiddle.
$.each(numberField, function (k, v) {
if ($(v).val() === "") {
x = Math.floor((Math.random() * 10) + 1);
($(v).val(x));
}
});
Take a look at the doc for the jQuery each function.

try this...
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if (this.value === "") { // should check the value inside the loop.. not outside
x = Math.floor((Math.random() * 10) + 1);
this.value = x;
}
});
demo

I think the problem is here:
numberField.val()
instead, use
$(this).val()
so ...
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
alert($(this).val());
if ($(this).val() === ""){
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
};
});
updated Fiddle
http://jsfiddle.net/aaronk85/eC48k/

You can match only the fields with no value like this:
$('input[type=number][value=""]').each(function () {
this.value=Math.floor((Math.random() * 10) + 1);
});
Here's the demo.

Related

HTML and Javscript field returning NaN, when field is blank

I am working on a webapp, and the formatting of the one text field is working almost perfectly, however, the only thing that is happening I do not want to happen is when I click out of the field and there is no value, it returns NaN
HTML
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
Javascript
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt){
var n = parseInt(this.value.replace(/\D/g,''),10);
fnf.value = n.toLocaleString();
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
Why is it returning NaN when I click out of the text field and it is blank, I would like it to return 0 instead, for example.
You can check the value and zero it out with if (isNaN(n)) n = 0;
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt) {
var n = parseInt(this.value.replace(/\D/g, ''), 10);
if (isNaN(n)) n = 0;
fnf.value = n.toLocaleString();
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if (myValue.indexOf("$") != 0) {
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
when you parse something empty string it will return NAN. try this on console:--
parseInt(''.replace(/\D/g,''),10)
try this code....
hope it will fill your requirments :)
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt){
var n
n = this.value.replace(/\D/g,'')
fnf.value = n;
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if(myValue.length === 0){ myValue = '0'}
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>

Formatting number as thousand using only Javascript

Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here
function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}
var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;
if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}
for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}
formattedNumber = substrings.join(',');
if (isNegative) {
formattedNumber = '-' + formattedNumber;
}
document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">
Some notes:
Because you want commas, the type is not a number, it's a string
Because you want to work on the input after you type, it's onkeyup not onkeypressed
I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7
i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
function reformatText() {
var x = document.getElementById('test').value;
x = x.replace(/,/g, ""); // Strip out all commas
x = x.reverse();
x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
x = x.reverse();
x = x.replace(/^,/, ""); // Remove leading comma
document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">
function numberWithCommas(x) {
var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
console.log(real_num);
document.getElementById('test').value = real_num;
}
<input type="number" id="test" onkeypress="numberWithCommas(this.value)">
Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">
$(function () {
$('#btnformat').on('input propertychange paste', function () {
var x = $('#btnformat').val();
$('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
});
});
if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/

Masking the values in a textbox using jQuery

I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $(this).val();
var CCNLength = CCNValue.length;
$.each(CCNValue, function(i) {
if (CCNLength <= 7) {
$("#txtCCN").val(CCNValue);
} //end if
if (CCNLength >= 8 && CCNLength <= 14) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, CCNLength).replace(/[0-9]/g, "*"));
} //end if
if (CCNLength >= 15) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g, "*") + CCNValue.substring(15));
} //end if
});
});
});
</script>
</head>
<body>
<input type="text" id="txtCCN" maxlength=19 />
</body>
</html>
But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
No need of any condition of length, substring and replace can be directly used on the string of any length safely.
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $.trim($(this).val());
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
val can also be used
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
$(this).val(function(i, v) {
return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
The same can be done in VanillaJS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('txtCCN').addEventListener('keyup', function() {
var value = this.value.trim();
this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
}, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Try It: Its 100% workable...
$(document).ready(function () {
$("#txtCCN").keyup(function (e) {
var CCNValue = $(this).val();
CCNValue = CCNValue.replace(/ /g, '');
var CCNLength = CCNValue.length;
var m = 1;
var arr = CCNValue.split('');
var ccnnewval = "";
if (arr.length > 0) {
for (var m = 0; m < arr.length; m++) {
if (m == 4 || m == 8 || m == 12) {
ccnnewval = ccnnewval + ' ';
}
if (m >= 6 && m <= 11) {
ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
} else {
ccnnewval = ccnnewval + arr[m];
}
}
}
$("#txtCCN").val(ccnnewval);
});
});
One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)
to
if(CCNLength >= 8)
This seems to maintain the functionality while cutting out some repetition in your code.
Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.
$(function () {
$("#cardnum").keyup(function (e) {
var cardNo = $(this).val();
//Add the indices where you need a space
addSpace.call(this, [4, 9, 14], cardNo );
//Enter any valid range to add mask character.
addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
});
function addSpace(spacePoints, value) {
for (var i = 0; i < spacePoints.length; i++) {
var point = spacePoints[i];
if (value.length > point && value.charAt(point) !== ' ')
$(this).val((value.substr(0, point) + " "
+ value.substr(point, value.length)));
}
}
function addMask(range, value) {
$(this).val(value.substring(0, range[0])
+ value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
+ value.substring(range[1]));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cardnum" maxlength="19" />

Word count jquery and stop user from typing

$(document).ready(function(){
$("input").keyup(function(){
if($(this).val().split(' ').length == 10){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Enter your name: <input type="text">
If the input is 1 2 3 4 5 6 7 8 9 the alert fired, I know it included the space. But how to stop user from adding more character (even space) when the limit is reached?
The problem can easily be simplified to disabling the spacebar when the max word count is reached:
this should work: http://jsfiddle.net/wznervgz/6/
<input data-max-words="10" />
js:
$('input[data-max-words]').on('keydown', function (e) {
var $txt = $(this),
max = $txt.data('maxWords'),
val = $txt.val(),
words = val.split(' ').length;
if (words === max && e.keyCode === 32)
return false;
});
Hope this will help you.
<textarea name="txtMsg" id="word_count" cols="1" rows="1"> </textarea>
<span style="padding-left:10px;">Total word Count :
<span id="display_count" style="font-size:16px; color:black;">0</span> words &
<span id="count_left" style="font-size:16px; color:black;">2</span> words left.</span>
<br>
jquery code:
var max_count = 2;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function (k, v) {
finalCount += v;
});
var vl = this.value;
if (finalCount > max_count) {
vl = vl.substring(0, vl.length - 1);
this.value = vl;
}
var countleft = parseInt(max_count - finalCount);
$('#display_count').html(finalCount);
$('#count_left').html(countleft);
am_cal(finalCount);
});
}).keyup();
Fiddle link: http://jsfiddle.net/aVd4H/32/
Thank you.
Think about storing the value of the input after each keyup and if the wordcount is greater than your limit just setVal back to the "previously" saved amount. So it would start off as var previousVal = ''; and then increment accordingly until the comparison returns true, set the val and return.
Demo: http://jsfiddle.net/robschmuecker/wznervgz/1/
$(document).ready(function(){
var previousValue = '';
$("input").keydown(function(){
if($(this).val().split(' ').length >= 10){
alert();
$(this).val(previousVal);
return;
}
previousVal = $(this).val();
});
});
You can try this:
$("input").keydown(function(e){
if($(this).val().split(' ').length == 10){
alert();
e.preventDefault();
return false;
}

Format numbers with jquery numberformatter and format them back

I format numbers of an input field with jquery numberformatter, that works, but I have to format them back in order to do some calculations on the numbers, but that doesn't work. How can I convert the formatted numbers back so that I can use the calculate function?
Here is the JS for the number formatting:
$("[id$='abzug']").keyup(function(){
$(this).parseNumber({format:"#,###", locale:"ch"});
$(this).formatNumber({format:"#,###", locale:"ch"});
val();
});
Here the HTML:
<input class="form-control" id="kunst_abzug" type="text">
<input class="form-control" id="theater_abzug" type="text">
And here the function to calculate the total:
function id(id){return document.getElementById(id);}
function val(){
val_totalEingespart = parseInt(id("totalEingespart").value) || 0;
val1 = parseInt(id("kunst_abzug").value) || 0;
val2 = parseInt(id("theater_abzug").value) || 0;
var total_abgezogen = val_totalEingespart - val1 - val2;
var total_abgezogenCHF = total_abgezogen.toLocaleString('de-CH');
id("totalSum2").innerHTML = total_abgezogenCHF + ' CHF';
}
I also created a js fiddle: http://jsfiddle.net/Lffpg4xp/2/
Remove the onkeyup="val() from each input element and add it to the keyup of function in document.ready.
$( document ).ready(function() {
$("[id$='abzug']").keyup(function(){
$(this).parseNumber({format:"#,###", locale:"ch"});
$(this).formatNumber({format:"#,###", locale:"ch"});
val();
});
});
function getElementValue(id){
var num = $('#' + id).val();
return $.parseNumber(num, {format:"####", locale:"ch"});
}
function val(){
val_totalEingespart = parseInt(getElementValue("totalEingespart")) ? parseInt(getElementValue("totalEingespart")) : 0;
val1 = parseInt(getElementValue("kunst_abzug")) ? parseInt(getElementValue("kunst_abzug")) : 0;
val2 = parseInt(getElementValue("theater_abzug")) ? parseInt(getElementValue("theater_abzug")) : 0;
var total_abgezogen = val_totalEingespart - val1 - val2;
$("#totalSum2")[0].innerHTML = total_abgezogen.toLocaleString('de-CH') + ' CHF';
}
Updated fiddle

Categories