jQuery: reverse string slice function? - javascript

I have simple code that will replace the characters in a string with '*' and only displays the last 4 characters of the string. Example:
string = 424242424242
Should become:
********4242
The code that does that is this:
var str = $('.cc').val();
var trailingCharsIntactCount = 4;
str = new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice( -trailingCharsIntactCount);
$('.cc').val(str);
Now, I need to reverse that when the users focus on an input field.
This is a working fiddle:
https://jsfiddle.net/s66k9x1s/1/
Basically, I need to show/hide the input's value the same way I demonstrated in my fiddle.
Could someone please advice on how I can achieve this?

The string replacement cannot be reversed from thin air,
you need to save the original value somewhere.
You could use jQuery's .data(), for example.
Store the original value with .data('value', str),
and when the field receives the focus,
restore it from .data('value').
function getMaskedValue(str) {
var trailingCharsIntactCount = 4;
return new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice(-trailingCharsIntactCount);
}
var $cc = $('.cc');
var str = $cc.val();
$cc.data('value', str);
$cc
.val(getMaskedValue(str));
.focus(function() {
$(this).val($(this).data('value'));
});
And as #aaron pointed out,
after focus is lost, you also want to restore the masked value:
$cc
.focus(function() {
$(this).val($(this).data('value'));
})
.blur(function() {
str = $(this).val();
$(this).data('value', str);
$(this).val(getMaskedValue(str));
});
He is also right that you don't need .data(),
you could store the real value in a variable.
It will be good to hide it within a closure.
(See fiddle.)
(function() {
function getMaskedValue(s) {
var masklen = s.length - 4;
return s.substr(0, masklen).replace(/./g, '*') + s.substr(masklen);
}
var $cc = $('.cc');
var value = $cc.val();
$cc
.val(getMaskedValue(value))
.focus(function() {
$(this).val(value);
})
.blur(function() {
value = $(this).val();
$(this).val(getMaskedValue(value));
});
})();
I also simplified the implementation of computing the masked value,
which should perform better, eliminating array operations.

Leave the original value in str. Here's a clean and simple answer that includes re-hide on blur:
var cc = $('.cc');
var str;
var trailingCharsIntactCount = 4;
function getHiddenValue() {
str = cc.val();
return new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice(-trailingCharsIntactCount);
}
cc.val(getHiddenValue());
cc.focus(function() { cc.val(str); });
cc.blur(function() { cc.val(getHiddenValue()); });

Related

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

Javascript - Incrementing specific numbers of a string

I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.

Validate user input for extra long words in textarea

I have a problem here with validating user's input in textarea.
A user is suppose to enter his description in one of the textarea feild in form. But some people just put the random text like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' or something to bypass the minimum length requirement.
Now i want to prevent user from typing such long text without any spaces since it disrupts the UI of my page.
Also a long text entered by user without any spaces can be a valid url too. So how do i manage this & throw a error to user to correct the text only if it is too long and it isnt a valid url ??
PS: I dont want to split string myself.. I just want to detect it and throw error to user on client side validation. Just to put end to some doubts, i will do server side validation in which i will forcibly enter a space and save it in DB. But i am expecting to solve this problem on client side
var STRING_MAX_LENGTH = 10;
var description = 'aaa aaaaaaaaaa bbbbbbbbbb http://www.google.com/search?q=client-side-filtering';
var array = description.split( ' ' );
$.each( array, function() {
if ( this.length >= STRING_MAX_LENGTH ) {
if( /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i . test( this ) ) {
alert( this + ' is an URL' );
} else {
alert( this + ' is not an URL' );
}
}
});
http://jsfiddle.net/vVYAp/
function validate()
{
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var wordLengthExpr = /\b[^\s]{50,}\b/;
var regex = new RegExp(expression);
var wordLengthRegex = new RegExp(wordLengthExpr);
var t = $("#myTextarea").val();
if (t.match(regex) || !t.match(wordLengthRegex))
{
//valid
}
else
{
//throw error
}
}
This is a two step process:
Determine if any words are too long.
If so, determine if they are valid URLs.
var validateWordLength = function (str) {
var maxLength = 50, // or whatever max length you want
reURL = /^(ftp|http|https):\/\/[^\s]+$/, // use whatever regular expression for URL matching you feel best
words = str.split(/\s+/),
i;
for (i = 0; i < words.length; i += 1) {
if (words[i].length > maxLength) {
// test for url
// but bear in mind the answer at http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript
// testing for url may not be fruitful
if (!reURL.test(words[i])) {
return false;
}
}
}
return true;
};
try this
var value = Your text;
var result = value.replace(" ","");
if(value.length == result .length)
//not valid
else
//valid
You can get length of each word, and then can decide whether to allow the user or not -
var arr = text.split(' ');
$.each(arr,function(){
console.log(this.length);
// check valid word length
});
http://jsfiddle.net/mohammadAdil/cNZtn/
If you use the jQuery validate plugin you can add a method to it:
jQuery.validator.addMethod("samechars", function(value, element) {
return this.optional(element) || !/([a-z\d])\1\1/i.test(value);
}, "Invalid input");
If you want to use jQuery you can use the following:
$("form").submit(function(e){
var $textarea = $('#msg'),
maxWordLength = 20;
var value = $textarea.val().split(' '),
longWord = false;
for(var n = 0; n < value.length; n++) {
if(value[n].length >= maxWordLength)
longWord = true;
}
if(longWord) {
alert('Too long word');
return false;
}
});
Here is a fiddle:
http://jsfiddle.net/pJgyu/31286/

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

I'm looking for an example of how to capitalize the first letter of a string being entered into a text field. Normally, this is done on the entire field with a function, regex, OnBlur, OnChange, etc. I want to capitalize the first letter while the user is still typing.
For instance, if I'm typing the word "cat", the user should press 'c', and then by the time he presses 'a', the C should be capitalized in the field.
I think what I'm going for might be possible with keyup or keypress but I'm not sure where to start.
Anyone have an example for me?
Just use CSS.
.myclass
{
text-transform:capitalize;
}
This will simply transform you first letter of text:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
I answered this somewhere else . However, here are two function you might want to call on
keyup event.
To capitalize first word
function ucfirst(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
And to capitalize all words
function ucwords(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
As #Darrell Suggested
$('input[type="text"]').keyup(function(evt){
// force: true to lower case all letter except first
var cp_value= ucfirst($(this).val(),true) ;
// to capitalize all words
//var cp_value= ucwords($(this).val(),true) ;
$(this).val(cp_value );
});
Hope this is helpful
Cheers :)
$('input[type="text"]').keyup(function(evt){
var txt = $(this).val();
// Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
$(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});
CSS solution with "text-transform: capitalize;" is no good if you want to use the contents of the input in backend. You will still receive data as-is. JavaScript solves this issue.
JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "Tro Lo-Lo":
Add to your script:
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
return $word.toUpperCase();
}));
box.setSelectionRange(stringStart , stringEnd);
});
return this;
}
Then just attach capitalize() to any selector:
$('#myform input').capitalize();
I used the code of #Spajus and wrote a more extended jQuery plugin.
I wrote these four jQuery functions:
upperFirstAll() to capitalize ALL words in an inputfield
upperFirst() to capitalize only the FIRST word
upperCase() to convert the hole text to upper case
lowerCase() to convert the hole text to lower case
You can use and chain them like any other jQuery function:
$('#firstname').upperFirstAll()
My complete jQuery plugin:
(function ($) {
$.fn.extend({
// With every keystroke capitalize first letter of ALL words in the text
upperFirstAll: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// With every keystroke capitalize first letter of the FIRST word in the text
upperFirst: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to lowercase
lowerCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase());
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to uppercase
upperCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toUpperCase());
box.setSelectionRange(start, end);
});
return this;
}
});
}(jQuery));
Groetjes :)
My personal favorite when using jQuery is short and sweet:
function capitalize(word) {
return $.camelCase("-" + word);
}
There's a jQuery plugin that does this too. I'll call it... jCap.js
$.fn.extend($, {
capitalize: function() {
return $.camelCase("-"+arguments[0]);
}
});
$("#test").keyup(
function () {
this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
}
);
Slight update to the code above to force the string to lower before Capitaliing the first letter.
(Both use Jquery syntax)
function CapitaliseFirstLetter(elemId) {
var txt = $("#" + elemId).val().toLowerCase();
$("#" + elemId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase(); }));
}
In addition a function to Capitalise the WHOLE string:
function CapitaliseAllText(elemId) {
var txt = $("#" + elemId).val();
$("#" + elemId).val(txt.toUpperCase());
}
Syntax to use on a textbox's click event:
onClick="CapitaliseFirstLetter('myTextboxId'); return false"
this will help you in - convert first letter of each word to uppercase
<script>
/* convert First Letter UpperCase */
$('#txtField').on('keyup', function (e) {
var txt = $(this).val();
$(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
return $1.toUpperCase( );
}));
});
</script>
Example : this is a title case sentence -> This Is A Title Case Sentence
My appologies. The syntax was off due to me being in a hurry and sloppy. Here you go...
$('#tester').live("keyup", function (evt)
{
var txt = $(this).val();
txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
$(this).val(txt);
});
Simple but works. You would def want to make this more general and plug and playable. This is just to offer another idea, with less code. My philosophy with coding, is making it as general as possible, and with as less code as possible.
Hope this helps. Happy coding! :)
It's very cool you can capitalize Only the first letter of an input field With this one.. If any one know how to capitalize Like CSS text-transform:capitalize, Please Reply ..
Here You go..
$('input-field').keyup(function(event) {
$(this).val(($(this).val().substr(0,1).toUpperCase())+($(this).val().substr(1)));
});
If using Bootstrap, add:
class="text-capitalize"
For example:
<input type="text" class="form-control text-capitalize" placeholder="Full Name" value="">
A turkish one. If someone is still interested.
$('input[type="text"]').keyup(function() {
$(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])|\s+([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])/g, function ($1) {
if ($1 == "i")
return "İ";
else if ($1 == " i")
return " İ";
return $1.toUpperCase();
}));
});
With Javascript you can use:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
If by chance you're generating your web page with PHP you can also use:
<?=ucfirst($your_text)?>
Jquery or Javascipt doesn't provide a built-in method to achieve this.
CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.
If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>
var capitalizeString = function (word) {
word = word.toLowerCase();
if (word.indexOf(" ") != -1) { // passed param contains 1 + words
word = word.replace(/\s/g, "--");
var result = $.camelCase("-" + word);
return result.replace(/-/g, " ");
} else {
return $.camelCase("-" + word);
}
}
I use both CSS and jQuery solutions when achieving this. This will change both how it appears in the browser and the data value. A simple solution, that just works.
CSS
#field {
text-transform: capitalize;
}
jQuery
$('#field').keyup(function() {
var caps = jQuery('#field').val();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
jQuery('#field').val(caps);
});
A solution that accept exceptions(passed by parameters):
Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);
(function($) {
$.fn.maskOwnName = function(not_capitalize) {
not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart,
end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
}
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
}
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
}
})(jQuery);
.first-character{
font-weight:bold;
color:#F00;
text-transform:capitalize;
}
.capital-text{
text-transform:uppercase;
}
My attempt.
Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names.
Happens on Blur as to not cause annoyances on phones.
Although left in selection start/end so if changed to keyup maybe useful still.
Should work on phones but have not tried.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var lc = txt.toLocaleLowerCase();
var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
box.setSelectionRange(stringStart, stringEnd);
}
});
return this;
}
// Usage:
$('input[type=text].capitalize').capitalize();
Slight update to cumul's solution.
The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,

Categories

Resources