Force first letter uppercase in input field - javascript

I'm practicing some JavaScript and would love to hear your thoughts regarding this script I wrote. I've managed to make this work. The script makes the first letter of the input value uppercase using the script below. I'm just wondering if this is a good method of doing this/if my steps are in good order just to get better
love to hear more ways of doing so, even making an option to eliminate the caps-lock via keyboard thanks,
// my input var
var strInput =document.querySelector("#inputText > input");
// my function and eventlistener
strInput.addEventListener('input',function() {
//upper case first letter with concatenate string input
var outputString = strInput.value.charAt(0).toUpperCase() + strInput.value.slice(1);
this.value = outputString;
});

As in the comments requested
Here is an example to bind the event to ALL text-inputs (except <textarea> and contenteditable="true")
var txtInputs = document.querySelectorAll("input[type='text'");
//just a simple validation if its not null, undefined or empty
if (txtInputs && txtInputs.length > 0) {
for (var i = 0; i < txtInputs.length; i++) {
var txtInput = txtInputs[i];
txtInput.addEventListener('input', function() {
var outputString = this.value.charAt(0).toUpperCase() + this.value.slice(1);
});
}

Related

Is it possible to extract time from a text comment using js?

First let me apologize for my ignorance when it comes to js.
Is it possible to extract a time from text? For example, i'd like to extract the time from the following text "Results phoned by _ to _ at 2018/04/12 01:31:33. Results confirmed. Read back."
Is this even possible to accomplish this? The software that I use allows for both js and BIRT coding. Any help would be appreciated.
var str = dataSetRow["Comment - Result"];
var time = str.match(/([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)/g);
time;
Outputs to "Ljava.lang.Object;#bd6334" and i have no idea how to fix it.
I get the "Ljava.lang.Object;#" error for every row of my table with different characters after the #
If I change the code to:
var str = dataSetRow["Comment - Result"];
var time = str.match(/\d{2}:\d{2}:\d{2}/g);
if (time.length>0) time [0];
else "";
I get the desired result but it will only display 1 row of a table with significantly more rows. Am I missing something?
Managed to get it working with some help from our system's manufacturer:
var str = dataSetRow["Comment - Result"];
var time = null;
if (str != null) time = str.match(/\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}/);
var output = "";
if (time != null) {
for (var i = 0; i < time.length; ++i) {
if (i > 0) output += "\n"; // this adds a line break in a computed column expression
output += time[i];
}
}
output;

Deleting part of string from hidden box - javascript

I have one hidden box which contains value like (,1420,1254,1258,124,1235). These values are IDs which are populated based on the description selected by user through Select Box. If user selects any description and removes it from Select Box then corresponding ID should be removed from the Hidden box. I can only use Javascript to do this. I tried using replace method but it is not supported and also my application works only in IE browser.
Could anyone let me know how to get this done?
TIA
Without seeing your code, this is the most we can help you with
function removeId(hiddenBox,id){
var idList = hiddenBox.innerHTML;
idList = idList.customReplace(','+id,'');
hiddenBox.innerHTML = idList;
}
And since you said the replace method is not working for some reason (which is weird), here is a custom replace method
I'm hoping the indexOf(), length and substring() methods are still working
String.prototype.customReplace = function(from,to){
var string = String(this);
var newString = "";
var startIndex = string.indexOf(from);
if(startIndex == -1) return string;
var endIndex = startIndex + from.length;
newString = string.substring(0,startIndex);
newString += to;
newString += string.substring(endIndex,string.length);
return newString;
}

How to properly strip HTML tags dynamically using javascript?

I know this type of question has been asked before, which is how I came up with my regular expression in the first place, but my coding doesn't seem to be working.
I'm combining 2 things, firstly I'm trying to restrict a multiline textbox to 6000 characters and have this work on key up, which it does nicely. However, as part of this I also want to strip out HTML tags BEFORE checking the length, which is the bit that's not working. My code is below:
function TruncateNotes(text) {
var notesfield = document.getElementById(text.id);
//strip html tags such as < and > out of the text before checking length
stripHTML(text);
var maxlength = 6000;
if (notesfield.value.length > maxlength) {
notesfield.focus();
notesfield.value = text.value.substring(0, maxlength);
notesfield.scrolltop = notesfield.scrollHeight;
return false;
}
else {
return true;
}
}
function stripHTML(text) {
var notesfield = document.getElementById(text.id);
notesfield.value.replace(/<.*?>/g, "");
}
My feeling is that's something to do with the regular expression as I'm not very good with those. Any suggestions?
JavaScript '.replace' does not modify the original string, it returns a string with the values replaced. This means you'll have to assign it back to notesfield.value after the operation:
notesfield.value = notesfield.value.replace(/<.*?>/g, "");

Regex not matching properly

Ive been working on this regex for days now and I cant get it figured out. It either passes everything I put in there or it kicks everything out and I cannot seem to make it function. Admittedly I am new to doing this complex of stuff with Javascript so It may be that you realy cant do this.
I want to check onkeypress what was entered into the input and then validate it to x, y, or z. Then from there send it on about its way to do other neat stuff.
So the question is what the heck am I not understanding about RegExp?
Here is a FIDDLE for it.
function val() {
var gradeIn = document.querySelectorAll("#letGrade input[type=text]");
var checkGrade = new RegExp(/[xyz]/gi);
for (var i = 0; i < gradeIn.length; i++) {
if (!checkGrade.test(gradeIn.value)) {
alert ("This must be X, Y, or Z");
return false;
} else {
return true;
}
}
};
EDIT/UPDATE:
I was trying to do this on keypress and validate each text input individualy however this was realy kinda squishy in the grand scheme of things and not working out exactly correct. I decided to validate all text inputs onsubmit and have everything go all at once. Updated code is below.
function calcGPA() {
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be A, B, C, D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
gVals.push(grades[i].value);
cVals.push(contacts[i].value);
}
//Other cool stuff happens here
};
Now to just finish the conversion piece for the letters to numbers and the math piece. Thank you for your help on this!
The problem's not only with your regular expression.
if (!checkGrade.test(gradeIn[i].value)) {
You weren't checking each grade. Now if you want it to only be those characters, you have to extend the regular expression a bit. Also, there's no point calling new RegExp if you're using native syntax.
var checkGrade = /^[xyz]+$/;
That means that you're OK with the fields being like "xxyyz" or "zzy". If it should just be one character, that'd be
var checkGrade = /^[xyz]$/;

Searching for most performant way for string replacing with javascript

I'm programming my own autocomplete textbox control using C# and javascript on clientside. On client side i want to replace the characters in string which matching the characters the user was searching for to highlight it. For example if the user was searching for the characters 'bue' i want to replace this letters in the word 'marbuel' like so:
mar<span style="color:#81BEF7;font-weight:bold">bue</span>l
in order to give the matching part another color. This works pretty fine if i have 100-200 items in my autocomplete, but when it comes to 500 or more, it takes too mutch time.
The following code shows my method which does the logic for this:
HighlightTextPart: function (text, part) {
var currentPartIndex = 0;
var partLength = part.length;
var finalString = '';
var highlightPart = '';
var bFoundPart = false;
var bFoundPartHandled = false;
var charToAdd;
for (var i = 0; i < text.length; i++) {
var myChar = text[i];
charToAdd = null;
if (!bFoundPart) {
var myCharLower = myChar.toLowerCase();
var charToCompare = part[currentPartIndex].toLowerCase();
if (charToCompare == myCharLower) {
highlightPart += myChar;
if (currentPartIndex == partLength - 1)
bFoundPart = true;
currentPartIndex++;
}
else {
currentPartIndex = 0;
highlightPart = '';
charToAdd = myChar;
}
}
else
charToAdd = myChar;
if (bFoundPart && !bFoundPartHandled) {
finalString += '<span style="color:#81BEF7;font-weight:bold">' + highlightPart + '</span>';
bFoundPartHandled = true;
}
if (charToAdd != null)
finalString += charToAdd;
}
return finalString;
},
This method only highlight the first occurence of the matching part.
I use it as follows. Once the request is coming back from server i build an html UL list with the matching items by looping over each item and in each loop i call this method in order to highlight the matching part.
As i told for up to 100 items it woks pretty nice but it is too mutch for 500 or more.
Is there any way to make it faster? Maybe by using regex or some other technique?
I also thought about using "setTimeOut" to do it in a extra function or maybe do it only for the items, which currently are visible, because only a couple of items are visible while for the others you have to scroll.
Try limiting visible list size, so you are only showing 100 items at maximum for example. From a usability standpoint, perhaps even go down to only 20 items, so it would be even faster than that. Also consider using classes - see if it improves performance. So instead of
mar<span style="color:#81BEF7;font-weight:bold">bue</span>l
You will have this:
mar<span class="highlight">bue</span>l
String replacement in JavaScript is pretty easy with String.replace():
function linkify(s, part)
{
return s.replace(part, function(m) {
return '<span style="color:#81BEF7;font-weight:bold">' + htmlspecialchars(m) + '</span>';
});
}
function htmlspecialchars(txt)
{
return txt.replace('<', '<')
.replace('>', '>')
.replace('"', '"')
.replace('&', '&');
}
console.log(linkify('marbuel', 'bue'));
I fixed this problem by using regex instead of my method posted previous. I replace the string now with the following code:
return text.replace(new RegExp('(' + part + ')', 'gi'), "<span>$1</span>");
This is pretty fast. Much faster as the code above. 500 items in the autocomplete seems to be no problem. But can anybody explain, why this is so mutch faster as my method or doing it with string.replace without regex? I have no idea.
Thx!

Categories