HTML forms auto caps lock - javascript

Is there a way to make it so that in an html form, someone types something, and it automatically makes it a capitol letter, like in a software key code input, I would like there to automatically be a dash inserted after every five characters, but not after the last one, meaning that when someone types:
xxxxxxxxxxxxxxxxxxxx
it will automatically be entered in to the form in real time as:
XXXXX-XXXXX-XXXXX-XXXXX
Is there a way to achieve this in real time? Here is my current code for the form:
<form name="key" autocomplete="off">
Key: <input type="text" name="key" maxlength="23"/>
<input type="submit" onclick="check(this.form)" value=" Submit "/>
</form>
<script language="javascript">
function check(form)
{
if (form.key.value == "XXXXX-XXXXX-XXXXX-XXXXX")
{
window.open('URL')
}
else
{
alert ("Invalid Key")
}
}
</script>

This is not optimal at all, but it works !
<script language="javascript">
$(function(){
var isCorrect = false;
$('#key_id').on('keyup',function() {
$(this).val(function(i, text) {
text = text.toUpperCase();
if (text.length < 5) {
isCorrect = false;
return text;
} else if (text.length >= 5 && text.length < 11 && (text.split("-").length - 1) < 1) {
isCorrect = false;
return text.substr(0,5) + '-' + text.substr(5,5);
} else if (text.length >= 11 && text.length < 17 && (text.split("-").length - 1) < 2) {
isCorrect = false;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5);
} else if (text.length >= 17 && text.length < 23 && (text.split("-").length - 1) < 3) {
isCorrect = false;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5) + '-' + text.substr(15,5);
} else if (text.length >= 23) {
isCorrect = true;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5) + '-' + text.substr(15,5);
} else {
isCorrect = false;
return text;
}
});
});
$("#my_form").submit(function(){
if(isCorrect) {
window.open('URL');
} else {
alert('invalid');
}
});
});
</script>
On the event keyup (releasing a key = letter/number), I do :
UpperCase
Return the text normally if less than 5 char
Return the text with '-' if more than 5 char but less than 10+1 char (the +1 is because we added '-'). Else return the text normally if already added the '-'
Return the text with 2 '-' if more than 10+1 char but less than 15+2 char (because 2 '-'). Else return the text normally if already added the 2 '-'.
And so on...
EDIT :
Updated code, you will need to use jQuery and put an id to your input id="key_id"
EDIT :
New code, easier for you to use it. Still needs jQuery (you can do it without, search on StackOverflow how to convert $(id).val() in pure javascript).
http://jsfiddle.net/f8BzW/1/

You could use css for the capitalization: text-transform: uppercase;
And with jquery + this plugin: http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("xxxxx-xxxxx-xxxxx-xxxxx-xxxxx");
});
check out the demo
So after reading the comments I decided to code it all out in a demo for you.
Here is the fiddle: http://jsfiddle.net/doppel/v3eLX/#&togetherjs=KgqxizB1Fc
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="./css/style.css">
<title></title>
</head>
<body>
<form name="key" autocomplete="off">
<label for="key">Key:</label><input type="text" name="key" id="key" style="text-transform:uppercase;" maxlength="23"/>
<input type="submit" onclick="check(this.form)" id="btn" value="Submit"/>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="jquery.maskedinput.js"></script>
<script language="javascript">
function check(form)
{
if (form.key.value == "XXXXX-XXXXX-XXXXX-XXXXX")
window.open('URL')
else
alert ("Invalid Key")
}
$("document").ready(function() {
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
});
</script>
</body>
Note you will have to download the plugin and include it like I have or copy the fiddle code.
So as you see I added a label because its proper,
I added an Id to the input to make it easier to select, Note I also added an in-line style to force Uppercase as stated above ^^^^.
Now the script $("document").ready(function() {gets jquery ready to be used.
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "}); This statement selects id key as the target of the function Mask which is the plugin to be called stating that we want a format aaaaa-aaaaa-aaaaa-aaaaa where a is equal to "letter". Note only "a" and "9" denote alpha and numeric data. And "{placeholder:" "})" the plugin by default puts underscores as placeholders but I changed it to a space to look more what you want I think.

Related

innerHTML property is not changing after JS function

I'm a fresher in JS, so I have the following task: Some text is given on a page and when a user wants to find a set of characters or string by adding this string in a window and then clicking "search", this string should be marked as bold in our text each time it is met.
Looking through my code I'm almost sure that the function is working, but after the function has finished, the bold strings just blink for a moment and the text returns to its initial status.
Please help me to find out my mistake.
Here's the code.
function look(a) {
var str = document.getElementById("original").innerHTML;
var len = a.text.value.length;
var begin = str.indexOf(a.text.value);
var final = str;
if (begin == -1) {
alert("No matches");
return false;
}
if (begin > -1) {
var count = 0;
final = str.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
while (begin != -1) {
begin = str.indexOf(a.text.value, begin + len);
if (begin == -1) break;
final = final.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
}
document.getElementById("original").innerHTML = final;
return true;
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<span id="original" type="text">Some given text</span>
<br/>
<form name="search" onsubmit="return look(this)">
<p>Enter text to search<input type="text" name="text"></p>
<p><input type="submit" value="search"></p>
</form>
</body>
Returning true on successfully finding the text span makes the form to be submitted. You need to return false to make the form invalidate the submission. This is the updated code, I have changed the return statement out of the if-else block and returned false either way. Another way is to make submit button as input[type='button'] and register an onclick event listener to it.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
}
return false;
}
The page is refreshing! By default, forms refresh the page. You can use the return value of the on submit function to stop this default behavior: just return false.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
return false;
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
return false;
}
}
<body>
<span id="original" type="text">
Some given text
</span>
<br/>
<form name="search" onsubmit="look(this); return false;">
<p>
Enter text to search<input type="text" name="text">
</p>
<p>
<input type="submit" value="search">
</p>
</form>
</body>
</html>

How to count the number of commas in a text box using javascript or jquery?

Upon clicking a submit button, I would like to do some client side validation to ensure there are fewer than 5 commas in a text box with the class of submit-btn. I can use javascript, jquery and/or regex here.
What code should I place within this function?
$('.submit-btn').on("click", function() {
<< WHAT GOES HERE? >>
});
Any help is greatly appreciated.
I use regex to find the number of times the string , occurs in the textbox value. It prints whether or not it is valid (having less than 5 commas).
$("#validate").click(function () {
console.log(($("#textboxInfo").val().match(/,/g)||[]).length < 5)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" />
<button id="validate">less than 5 commas?</button>
Automatically responding to user input
In this particular situation, I'd prefer to have live validation. This can be accomplished by using the input event.
$("#textboxInfo").on('input', function () {
var isValid = ($(this).val().match(/,/g) || []).length < 5;
$(".isValid").html(isValid ? "Valid" : "Invalid");
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" value="I really love ,,, commas!" />
<div class="isValid"> </div>
Split the value of the input box and filter out , and check the length of it
$('.submit-btn').on("click", function() {
var getNumbers = $('#testBox').val().split('').filter(function(item) {
return item === ','
}).length;
console.log(getNumbers)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='testBox'>
<button class='submit-btn' type="button">Click</button>
You could try using this Comma Counter
$('button').on('click',function(){
var counter = ($('div').html().match(/,/g) || []).length;
$('.result').text(counter);
}
)/
You could also remove everything that is not a comma [^,], replace that with an empty string and count the length of the string.
$('.submit-btn').on("click", function() {
var nr = $("#tbx").val().replace(/[^,]/g, "").length;
console.log("Fewer than 5 commas? " + (nr < 5 ? "Yes" : "No") + " there are " + nr + " commas.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='tbx'>
<button class='submit-btn' type="button">Click</button>

How to capitalize first letter of EACH WORD, in input type text [duplicate]

This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 5 years ago.
$(document).ready(function () {
$(document).on('keydown', '.FIRSTNAME',
function (event) {
if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey) && !(event.ctrlKey) && !(event.metaKey) && !(event.altKey)) {
var $t = $(this);
event.preventDefault();
var char = String.fromCharCode(event.keyCode);
$t.val(char + $t.val().slice(this.selectionEnd));
this.setSelectionRange(start, end);
}
});
});
can you use my code and edit it?
the difference is the first letter in every word...
I just want to capitalize the first letter in every word
someone help me... tnx in advance
No need of using the javascript. You can simply do it in CSS using text-transform: capitalize; like this
<input type='text' name='name' class='name' style="text-transform: capitalize;" placeholder='Enter your name here'/>
jquery this way easy capitalize first letter of EACH WORD, in input type text
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div><label>Capitalize the first letter of all words in a string: </label><input type="text" id="txt_firstCapital" name="txt_firstCapital" /></div>
<script>
jQuery(document).ready(function() {
jQuery('#txt_firstCapital').keyup(function()
{
var str = jQuery('#txt_firstCapital').val();
var spart = str.split(" ");
for ( var i = 0; i < spart.length; i++ )
{
var j = spart[i].charAt(0).toUpperCase();
spart[i] = j + spart[i].substr(1);
}
jQuery('#txt_firstCapital').val(spart.join(" "));
});
});
</script>
function capitalize(obj)
{
obj.value = obj.value.split(' ').map(eachWord=>
eachWord.charAt(0).toUpperCase() + eachWord.slice(1)
).join(' ');
}
<input type='text' id='textfield' onkeyup='capitalize(this)'>
This can be done with this function in JS
function firstCap(str)
{
return str.toString().replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() +
txt.substr(1).toLowerCase();});
}
You only needed css to fix it. Add the below code in your css.
.FIRSTNAME{
text-transform: capitalize;
}
OR try this
<input type="text" id="txtval" style="text-transform:capitalize" />
this works
NB: There is no need of jquery for this.

Getting function to run as user types

I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>

Javascript and HTML form validation checks

i am trying to learn html and javascript. I have created an html form and am using javascript to validate the fields. I have a isNaN check for the age field, a regex check for emial and a presence check for all fields. I am currently outputting the form to the address bar but this does not work as i am getting errors.
<title> </title>
<script type="text/javascript">
function validate()
{
var errors = 0;
if (isNumeric(document.getElementById("age").value) == false)
{
errors++;
}
if (emailCheck(document.getElementById("email").value) == false)
{
errors++;
}
var inputBoxes = document.getElementsByTagName('input');
for(var i= 0; i < inputBoxes.length; i++)
{
if(inputBoxes[i].type != 'text') continue;
if(presenceCheck(inputBoxes[i].value) == false)
{
errors++;
}
}
console.log(errors);
if(errors == 0)
{
window.location.assign("output.html#" + "%%" + "name" + "%%" +
document.getElementById("name").value + "%%" + "email" + "%%" +
document.getElementById("email").value + "%%" + "age" + "%%" +
document.getElementById("age").value + "%%" + "comments" + "%%" +
document.getElementById("comments").value);
}
}
function isNumeric(number)
{
return !isNaN(number) && number != null && number != "";
}
function emailCheck(email)
{
var emailRegex = /\s+#\s+.\s+/;
return emailRegex.test(email);
}
function presenceCheck(data)
{
var regex = /\s+/;
return regex.test(data);
}
</script>
Below is the form which is just incased in body tags at the moment
<form id="frmA" name="frmA">
<label name="frmName">Name:</label><br />
<input form="frmA" type="text" name="frmName" id="name"/><br />
<label name="frmEmail">E-Mail:</label><br />
<input form="frmA" type="text" name="frmEmail" id="email"/><br />
<label name="age">Age:</label><br />
<input form="frmA" name="frmAge" id="age"/><br />
<label name="frmComments">Comments:</label><br />
<textarea form="frmA" cols="50" rows="10" id="comments"></textarea><br />
</form>
<button onClick="validate();">Submit</button>
i know that the checks work when no data is present however when i input data in the form and hit submit i am still faced with 4 errors. (there are 5 errors with no data: 3x presence checks, 1 for the regex and one for the isNaN)
My question therefore is why am i still getting errors and why do i get no output.
Any help would be greatly appreciated.
Extra: i would also like the input fields to change colour when there is an error.
Your regexes are wrong. You have /\s+#\s+.\s+/ and it should be /\w+#\w+\.\w+/. You didn't escape the dot and \s matches whitespace, not strings. \w matches word. For a proper email regex you would need much more than that but for your simple case to work this will suffice. The second regex should be /\w+/.

Categories