Fromat a TextField as soon as it's written to - javascript

I am trying to update a TextField as soon as the user types something in. I like to avoid people writing in different text formats but have the proper capitlisation eg. instead of jOHN or JOHN or john, the Text needs to be updated (firstCapitalLetter) John in this case.
I tried to copy the method as described here: Format input text to uppercase but I am failing to adapt it to my case. The txtFirstName is the ID of the TextField.
NWF$(document).ready(function () {
NWF$("#" + txtFirstName).change(function () {
// get the text value from the FirstNname textfield
var textContent = NWF$('#' + txtFirstName).text();
// check to see if the value is not null
if (textContent.length > 0) {
// format the first letter to UpperCase and the rest to LowerCase
textContent = NWF$("#" + txtFirstName).toUpperCase() + txtFirstName.substr(1).toLowerCase();
NWF.value = textContent;
}
});
});

I managed to get it working, after so many trials.
Now, the txtFirstName changes the format as wanted :)
NWF$(document).ready(function () {
NWF$("#" + txtFirstName).change(function () {
// get the text value from the FirstNname textfield
var textContent = this.value;
// check to see if the value is not null
if (textContent.length > 0) {
// format the first letter to UpperCase and the rest to LowerCase
textContent = textContent[0].toUpperCase() + textContent.substr(1).toLowerCase();
this.value = textContent;
}
});
});

Here is another option if you have to update two seperate txtFields.
Maybe one of you can propose a better approach on this.
Basically, I wanted to say, when the the txtFields are updated then they need to be formatted to the proper capitalisation to avoid things like: john / JOHN / jOHn
NWF$(document).ready(function () {
NWF$("#" + txtFirstName).change(function () {
// get the text value from the FirstNname textfield
var textContent = this.value; //alert(textContent)
// check to see if the value is not null
if (textContent.length > 0) {
// format the first letter to UpperCase and the rest to LowerCase
textContent = textContent[0].toUpperCase() + textContent.substr(1).toLowerCase();
this.value = textContent;
}
});
NWF$("#" + txtLastName).change(function () {
// get the text value from the FirstNname textfield
var textContent = this.value; //alert(textContent)
// check to see if the value is not null
if (textContent.length > 0) {
// format the first letter to UpperCase and the rest to LowerCase
textContent = textContent[0].toUpperCase() + textContent.substr(1).toLowerCase();
this.value = textContent;
}
});
});

Related

Formatting input type="text" in JS

I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.
I have the following code:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?
I was referred to a few other posts on Stack Overflow, but nothing seems to work out.
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g,''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.
function formatNumber(number) {
var str = number.toString();
var offset = str.length % 3;
var newStr = '';
for (var i = 0; i < str.length; i++) {
if (i > 0 && i % 3 === offset) {
newStr += ',';
}
newStr += str[i];
}
console.log(str, '=>', newStr);
}
formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.
Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):
const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);
function handleChange(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
values.value = formatted;
}
<input id="values" type="text">
The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e) and format it back to a number.
This makes sure you won't get NaN when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

should not allow more than one space in between words

function stripspaces(input)
{
input.value = input.value.replace(/\s+/gi," ");
}
I written this function. It is working but when I point the mouse pointer or moving with left arrow in between word and giving space it is jumping to the last. Can anyone give me the solution?
You can prevent the input by calling e.preventingDefault we can simply test if the space key has been pressed and if there's a space either side of the cursor then prevent entry.
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('myInput');
input.addEventListener('keydown', function(e){
var input = e.target;
var val = input.value;
var end = input.selectionEnd;
if(e.keyCode == 32 && (val[end - 1] == " " || val[end] == " ")) {
e.preventDefault();
return false;
}
});
});
<input type="text" id="myInput">
This still has the issue that it won't prevent pastes into the box with double spaces. So it may be worth still replacing multiple spaces on focus loss to be sure that the input never contains multiple contiguous spaces.
I just came across the same use case. If you also want to handle copy/paste or any other way the input's value could change, use the input event:
document.addEventListener('DOMContentLoaded', function() {
// get a reference to the input element
const input = document.querySelector('#myInput');
// guard clause to check if `#myInput' actually exists in the current DOM
if(!input) return
// Run this every time the input's value changes
input.addEventListener('input', e => {
// get the value
const value = e.target.value
// check if the value isn't exactly ' ' and ends with a space
const hasTrailingSpace = value !== ' ' && value.charAt(value.length-1) === ' '
// extract words, remove empty words (handles double spaces)
const words = value.split(' ').filter(el => el !== '')
// create the sanitized value
let sanitizedValue = words.join(' ')
// add a trailing space if there was one
if( hasTrailingSpace ) sanitizedValue += ' '
// apply the sanitized value to the input's value
e.target.value = sanitizedValue
})
})
<p>Try inserting double spaces now! Also try copy/paste from somewhere else</p>
<input type="text" id="myInput">

Incorrect Placement of Comma in Sum

I have a table with a text input on each line. Users can specify a dollar amount within each text box. My code loops through each text input and simply sums up the values. My problem is that when a user enters a value over >= 1,000,000 the sum becomes incorrect. For example, when a user enters 1,000,000 the sum is 1,000.
function init_icheck() {
$('#datatable input[type=checkbox]').iCheck({
checkboxClass: 'icheckbox_square-blue',
increaseArea: '10%'
});
}
// When Pay in Full Checkbox is Checked fill in Pay This Time Field with Invoice Amount Due Value
function paynow() {
var payFull = $('input[type="checkbox"].payfull');
payFull.on('ifChecked', function(event) {
$(this).parents('tr').find('.paynow').val($(this).val().replace('$', ''));
CalcFooter();
});
}
// If Pay in Full Unchecked then remove value from respective Pay This Time Input
// Only bind the ifUnchecked event if the checkbox is checked
function remove_checkbox() {
var payFull = $('input[type="checkbox"].payfull');
payFull.on('ifUnchecked', function(event) {
if ($(this).parents('tr').find('.paynow').val() == $(this).val().replace('$', '')) {
$(this).parents('tr').find('.paynow').val('');
CalcFooter();
}
});
}
// If Pay This Time changes recalculate total
function recalc_total() {
$('.paynow').keyup(function() {
var $ThisCheck = $(this).parents('tr').find('.payfull');
// Add Commas if # is over 1,000
$(this).val(addCommas($(this).val().replace(/,/g, '')));
if ($(this).val() == $ThisCheck.val().replace('$', '')) {
$ThisCheck.iCheck('check');
} else {
$ThisCheck.iCheck('uncheck');
}
CalcFooter();
});
}
// Recalc Function
function CalcFooter() {
var amtPage = 0;
var amtTotal = 0;
var Sum = 0;
$('.paynow').each(function(index, Obj) {
var value = parseFloat($(this).val().replace(',', ''));
if (!isNaN(value)) amtPage += value;
});
$('#datatable').DataTable().$('.paynow').each(function(index, Obj) {
var value = parseFloat($(this).val().replace(',', ''));
if (!isNaN(value)) amtTotal += value;
});
$('#amounttopay').text(
'Page: $' + addCommas(amtPage.toFixed(2)) +
' / Total: $' + addCommas(amtTotal.toFixed(2))
);
}
// Add Commas if value > 1,000
addCommas = function(input) {
// If the regex doesn't match, `replace` returns the string unmodified
return (input.toString()).replace(
// Each parentheses group (or 'capture') in this regex becomes an argument
// to the function; in this case, every argument after 'match'
/^([-+]?)(0?)(\d+)(.?)(\d+)$/g,
function(match, sign, zeros, before, decimal, after) {
// Less obtrusive than adding 'reverse' method on all strings
var reverseString = function(string) {
return string.split('').reverse().join('');
};
// Insert commas every three characters from the right
var insertCommas = function(string) {
// Reverse, because it's easier to do things from the left
var reversed = reverseString(string);
// Add commas every three characters
var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');
// Reverse again (back to normal)
return reverseString(reversedWithCommas);
};
// If there was no decimal, the last capture grabs the final digit, so
// we have to put it back together with the 'before' substring
return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
}
);
};
// Reinitialize iCheck on Pagination Change
$('#datatable').on('draw.dt', function() {
init_icheck();
paynow();
recalc_total();
remove_checkbox();
CalcFooter();
});
// Initialize Datatables
$('#datatable').dataTable({
"stateSave": true,
"oLanguage": {
"sSearch": "Search Results:"
}
});
I have a simple jsfiddle that illustrates this issue. I thank you in advance for pointing me in the right direction.
http://jsfiddle.net/tgf59ezr/14/
Using .replace(',', '') only replaces the first instance of the searched string, causing the number parsing to not work as intended.
Use this instead:
.replace(/,/g, '')
The g means replace all instances.
http://jsfiddle.net/da03j0aa/
Reference: String.prototype.replace()

Internal Site Search Jquery against a RegExp

Where am I going wrong? Even one error would help please.
I have an HTML input and a submit button. The idea is to:
Submit search string
Get string value.
Compare string value to regex.
If legit, find instances of the string in the DOM.
Then scroll to the first instance of the matched string as it sits in the DOM.
$("#submit").on("click", function () {
//regex to be compared against
var search = new RegExp();
search = /(^\w[A-z]+)$|(^\d[0-9\.x\.X\.m\.M]+)/;
//grab the string value from the search input
var userin = $("#searchin").val();
var compare = userin.test(search);
if (compare === true) {
var treebody = $('html, body').contents().filter(function (userin) {
if ($('html, body').contents() === userin) {
$('html, body').animate({'scrollTop' : $(treebody).position().top}, 700)
} else {
alert("Please search again or scroll down to find your desired content");
}
});
} else {
alert("Sorry, we couldn't match your search. Please try a region or place or a billboard size e.g. 9x13 ");
}
});
Change the line
var compare = userin.test(search);
it should be
var compare = search.test(userin);
Also check you regular expression. Here is a good reference RegEx.

Categories