jQuery number format for HTML input number with dynamic decimals - javascript

I've seen a lot of similar threads or library but I haven't found one I need.
I have preexisting code with many input[type=number] in the forms. I need to format the number value to local format when form is viewed at first load or when cursor/pointer is out of focus (onblur), and unformat the number to raw input when onfocus or when the form is submitted. The format are dot as separator and comma as decimal. The decimal numbers are dynamic, some don't have decimals, some have 2 or 4, or in other words, the decimal format is only shown when the number has decimal. And when a field doesn't have any value, still displays an empty string ("") not zero (0). A field that has 0 value still displays a 0.
Example:
//Number is 1400.45
//Document ready: 1.400,45
//Onfocus: 1400.45
//Onblur: 1.400,45
//Onsubmit value send by PHP page load: 1400.45
Is there any way to do this or jQuery/javascript library for this?

I don't think there is a library for such a specialized solution you are looking for but you can do it on your own.
That's the idea:
String.prototype.replaceLast = function(find, replace) {
var index = this.lastIndexOf(find);
if (index >= 0) {
return this.substring(0, index) + replace + this.substring(index + find.length);
}
return this.toString();
};
let transformValue = function(value) {
value = parseFloat(value);
value = parseInt(value).toLocaleString() + '.' + parseInt(value.toString().split('.')[1] || '0');
value = value.replace(',', '.');
value = value.replaceLast('.', ',');
return value;
};
let form = document.querySelector('#myForm');
window.addEventListener('load', function() {
let inputs = form.querySelectorAll('input[type="text"]');
for (let i = 0; i < inputs.length; i++) {
let input = inputs[i];
input.value = transformValue(input.value);
input.onfocus = function() {
this.value = this.value.replaceAll('.', '').replace(',', '.');
};
input.onblur = function() {
this.value = transformValue(this.value);
};
}
});
form.onsubmit = function() {
let inputs = form.querySelectorAll('input[type="text"]');
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = inputs[i].value.replaceAll('.', '').replace(',', '.'); }
for (let i = 0; i < inputs.length; i++) {
alert('submitted value ' + inputs[i].value);
}
};
#myForm {
display: flex;
flex-direction: column;
}
#myForm input {
outline: none;
border: 1px solid #000;
border-radius: 3px;
margin: 5px 0;
padding: 3px 7px;
}
<form id="myForm">
<input type="text" value="1400.45">
<input type="text" value="1401.45">
<input type="text" value="1402.45">
<input type="submit">
</form>

The below solution is totally dynamic, as wherever you want to put decimal position.
var num;
$(document).ready(function(){
num=$(".nums").val();
var nstring=num.replace(/\D/g,'');
var total_strings=nstring.length;
totalz=pad("1", (total_strings));
var nums=eval(nstring/totalz);
nums=""+nums+"";
var new_array=nums.split(".");
var val_1=addCommas(new_array[1]);
var narray=new_array[0]+"."+val_1;
$(".nums").val(narray);
});
$(".nums").focus(function(){
var numz=num;
$(".nums").val(numz);
});
$(".nums").blur(function(){
num=$(".nums").val();
var nstring=num.replace(/\D/g,'');
var total_strings=nstring.length;
totalz=pad("1", (total_strings));
var nums=eval(nstring/totalz);
nums=""+nums+"";
var new_array=nums.split(".");
var val_1=addCommas(new_array[1]);
var narray=new_array[0]+"."+val_1;
$(".nums").val(narray);
});
$(".nums").focus(function(){
var numz=num;
$(".nums").val(numz);
});
$(".form1").submit(function(){
var numz2=num;
$(".nums").val(numz2);
$(".form1").submit();
});
function pad (str, max) {
str = str.toString();
return str.length < max ? pad(str+"0", max) : str;
}
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form1" action="submit.php" method="post">
<input type="text" name="num" class="nums" value="1.40045">
<input type="submit">
</form>

Related

While Loop Input Issue

I am trying to make a program that takes numbers from the user until they input a 0, the output how many positive and negative numbers were input, while also telling the user whether the number they input was positive, negative, or zero, however, when I use it, it crashes the webpage immediately if anything but a 0 is input. So I was wondering where this issue would be coming from and how I could resolve it.
JS:
var pos = 0;
var neg = 0;
var inp = 1;
function interpreter() {
while (inp != 0) {
inp = (document.getElementById("number"));
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML = pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML = neg + " negative numbers were inputted";
}
}
}
Where "number" is a text field for input, and the function is called upon the press of a button. Thanks in advance!
You're misunderstanding the event-processing nature of JavaScript.
If you have a while loop like that, you'll never yield control back to the browser itself, to handle user input, etc. You may be looking for something like this -- in addition to the removal of the explicit loop, note how the handling of inp has changed; previously you were comparing strings to numbers.
var pos = 0;
var neg = 0;
function interpret() {
var inp = parseInt(document.getElementById("number").value);
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML =
pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML =
neg + " negative numbers were inputted";
}
}
<form onsubmit="interpret();event.preventDefault()">
<input id="number">
<input type="submit" value="Interpret value">
</form>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
If you really want my suggest:
var pos = 0
, neg = 0
;
document.forms['my-form'].addEventListener('submit',function(evt)
{
evt.preventDefault()
let inp = this.number.valueAsNumber
{
if (inp < 0)
{
this.out_1.textContent = 'Input is: negative'
neg++
}
else if (inp > 0)
{
this.out_1.textContent = 'Input is: positive'
pos++
}
else
{
this.out_1.textContent = 'Input is: zero';
this.out_2.textContent = pos + ' positive numbers were inputted'
this.out_3.textContent = neg + ' negative numbers were inputted'
}
}
})
label, button, output { display: block; margin:.4em; }
<form name="my-form">
<label>
Input:
<input name="number" type="number" min="-32768" max="32768" value="1">
</label>
<button type="submit"> enter </button>
<output name="out_1"></output>
<output name="out_2"></output>
<output name="out_3"></output>
</form>

Is there a way to split inserted value for example 1234567890 to 12345 and 67890?

Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);

How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?

enter image description here
How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?
You can check if the character of the string is uppercase by comparing the ASCII code. If it's between 65 & 90, the character is in uppercase.
Then by applying toUpperCase & toLowerCase methods will transform uppercase alphabets into lowercase and vice-versa.
function isUpperCase(c) {
return c >= 65 && c <= 90;
}
var string = "AaBbCcDd *+-";
var updatedString = string.split("").map(c => isUpperCase(c.charCodeAt(0)) ? c.toLowerCase() : c.toUpperCase()).join("");
console.log("Original String:: " + string);
console.log("Transformed String:: " + updatedString);
You can use this code alternate character
function alternate(changeString) {
var charArray = changeString.toLowerCase().split("");
for (var i = 1; i < charArray.length; i += 2) {
charArray[i] = charArray[i].toUpperCase();
}
return charArray.join("");
};
var text = "Test";
console.log(alternate(text));
For the transformation, you can use the following:
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
}
A complete example here: (although it isn't exact the same that is in your pic)
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
return result;
}
$('#text').on('input', function(){
$('#display').val(convert(this.value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>input</label><input id="text" />
<label>display</label><input id="display" disabled />
Please refer below code may be it will help you,
Keyup event will work each character
$(document).ready(function(){
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
$("#text").keyup(function(){
var l =this.value.length;
var s =this.value;
var r =new Array();
for(var i=0;i<l;i++){
if(upperCase.test(s[i])){
r.push(s[i].toString().toLowerCase());
}
if(lowerCase.test(s[i])){
r.push(s[i].toString().toUpperCase());
}
}
$("#res").val(r.toString().replace(/\,/g, '').trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<br>
Result:<input type="text" id="res">

Improving Secure Password Generator

Simple Password Generator Example:
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOP" +
"1234567890" +
"#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/",
pass = "",
PL = 10;
for (var x = 0; x < PL; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword();
}
<form name="myform" method="post" action="">
<table width="100%" border="0">
<tr>
<td>Password:</td>
<td>
<input name="row_password" type="text" size="40">
<input type="button" class="button" value="Generate" onClick="generate();" tabindex="2">
</td>
</tr>
</table>
</form>
Improving Functionality Questions
1). Obtaining All Values Within Variable
Taking the base script above, how can I call chars.length and chars.charAt(i) where chars equals all the values within Chars?
var Chars = {};
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
2). Implementing a checkbox system for less advanced password
To generate a less advanced password, such as not including symbox via unchecking a checkbox, how can I make it so only Chars.abc, Chars.ABE, and Chars.Num values are used?
3). Equally Divide Password Length By Chars
Round down (Password length / Chars used ), ie; the example used in this question generates a 10 character password and uses all charecters, therefore there would be a minimum of 2 of each Chars.
The 3rd functionality is missing and will probably be way more sophisticated. But this is a simple solution to the 1st and 2nd ones.
var output = document.getElementsByTagName('output')[0];
var Chars = {};
Chars.length = 16;
Chars.abc = "abcdefghijklmnopqrstuvwxyz";
Chars.ABE = "ABCDEFGHIJKLMNOP";
Chars.Num = "1234567890";
Chars.NumRequired = true;
Chars.Sym = "#\#\-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/";
var generator = new randomPasswordGenerator(Chars);
var simpleGenerator = new randomPasswordGenerator({
length: 6,
abc: 'abc',
Num: '0'
});
var button = document.getElementsByTagName('button')[0];
button.addEventListener('click', clickFunction);
var checkbox = document.getElementsByTagName('input')[0];
function clickFunction () {
if (checkbox.checked) output.textContent = simpleGenerator.randomPassword();
else output.textContent = generator.randomPassword();
}
function randomPasswordGenerator(opts) {
for(var p in opts) this[p] = opts[p];
this.randomPassword = randomPassword;
}
function randomPassword() {
var chars = (this.abc || "") +
(this.ABE || "") +
(this.Num || "") +
(this.Sym || ""),
pass = [],
PL = this.length;
if (this.NumRequired) {
var r = Math.floor(Math.random() * this.Num.length);
var i = Math.floor(Math.random() * PL);
pass[i] = this.Num[r];
}
for (var x = 0; x < PL; x++) {
if(!pass[x]) {
var i = Math.floor(Math.random() * chars.length);
pass[x] = chars.charAt(i);
}
}
return pass.join('');
}
output {
margin: 12px;
display: block;
border-bottom: 1px solid
}
<button>Generate</button>
<input type="checkbox">Simple
<output></output>

Unable to call function within jQuery

I am trying to call a function in this javascript code. My code needs to check for whether the user selects var num, var letters and var symbols to be true or false. In the code, I preset the values but I still search the object choices for the variables that are true and push it into the array choices_made. However, since I need to randomly choose the order in which the num, letters and symbols appear, I randomly choose the class based on the Math.random(). However, it doesn't show me the alert(jumbled_result) afterwards.
http://jsfiddle.net/bdaxtv2g/1/
HTML
<input id="num" type="text" placeholder="Enter desired length">
<br/><br/>
<input id="press" type="button" value="jumble it up">
JS
$(document).ready(function(){
var fns={};
$('#press').click(function(){
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
function gen(len, num, letters, sym){
var choices = {
1:num,
2:letters,
3:sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for(x in choices){
if(choices[x]==true){
choice_made.push(x);
}
}
for(i=0;i<len;i++){
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length-1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result){
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
});
You never declare functions within document.ready of jQuery. The functions should be declared during the first run(unless in special cases).
Here is a working code made out of your code. What I have done is just removed your functions out of document.ready event.
$(document).ready(function() {
$('#press').click(function() {
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
});
var fns = {};
function gen(len, num, letters, sym) {
var choices = {
1: num,
2: letters,
3: sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for (x in choices) {
if (choices[x] == true) {
choice_made.push(x);
}
}
for (i = 0; i < len; i++) {
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length - 1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result) {
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="num" type="text" placeholder="Enter desired length">
<br/>
<br/>
<input id="press" type="button" value="jumble it up">
Its because of the way the object choices have been intitialized.. Try this..
var choices = {
0:num,
1:letters,
2:sym
};
And also
var choice_made = [];
JS fiddle link : http://jsfiddle.net/8dw7nvr7/2/

Categories

Resources