Truncate width function not working when passing integer - javascript

I'm trying to create a universal function that I can call from multiple places to truncate long text recursively to fit a predefined pixel width - using jquery.
Here is the code...
function constrain(text, original, ideal_width){
var ideal = parseInt(ideal_width);
$('span.temp_item').remove();
var temp_item = ('<span class="temp_item" style="display:none">'+ text +'</span>');
var item_length = text.length;
$(temp_item).appendTo('body');
var item_width = $('span.temp_item').width();
if (item_width > ideal) {
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original);
} else if (item_length != original) {
return (text + '…');
} else if (item_length == original) {
return text;
}
}
If I run the function like this:
$('.service_link span:odd').each(function(){
var item_text = $(this).text();
var original_length = item_text.length;
var constrained = constrain(item_text, original_length,'175');
$(this).html(constrained);
});
The text doesn't truncate. I also tried the 175 without the quotes.
If I define var ideal = 175; inside the function, then it works. Why is passing 175 to the function not working? I did a parseInt on it in case it was a string.
Also - this truncate code run a bit slow on older machines - any tips for speeding it up?
Thanks!

Great stuff here. I used the function by Phil Carter. I just wanted the new string with the &hellip to be truncated at the same width as the rest.
I just quickly added another temp-width lookup and recursive call. Could use some cleanup but it works.
here's the new while:
while(item_width > ideal) {
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original, ideal_width, counter);
}
if (item_length != original) {
new_text=text+'…';
$('span.temp_item').remove();
var temp_item = ('<span class="temp_item" style="display:none">'+ new_text +'</span>');
$(temp_item).appendTo('body');
var item_width_new = $('span.temp_item').width();
if(item_width_new>ideal){
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original, ideal_width, counter);
}
else {
return new_text;
}
} else if (item_length == original) {
return text;
}
}

What happens when the visitor to your site presses "ctl +" ? It's my (probably out of date) belief that you're supposed to use "em" sizes for font containers, so they scale.

Ah... found the bug - forgot to pass the recursive part the ideal width:
return constrain(smaller_text, original, ideal);

TOTAL WE WRITE
So I decided that your iteration over the lorum ipsum text in 5 spans, taking 16 secs was far too long, so thought how to speed this up. and I have it down to 0.4 seconds.
function constrain(text, original, ideal_width, counter){
var ideal = parseInt(ideal_width);
$('span.temp_item').remove();
var temp_item = ('<span class="temp_item" style="display:none">'+ text +'</span>');
var item_length = text.length;
$(temp_item).appendTo('body');
var item_width = $('span.temp_item').width();
if(counter == 0) {
//work out some ranges
var temp_item = ('<span class="temp_item_i" style="display:none">i</span>');
$(temp_item).appendTo('body');
var i_width = $('span.temp_item_i').width();
var max_i = Math.round((ideal_width / i_width) + 1);
var temp_item = ('<span class="temp_item_m" style="display:none">M</span>');
$(temp_item).appendTo('body');
var m_width = $('span.temp_item_m').width();
var max_m = Math.round((ideal_width / m_width) + 1);
text = text.substr(0, (max_i - max_m));
var item_length = text.length;
}
counter++;
while(item_width > ideal) {
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original, ideal_width, counter);
}
if (item_length != original) {
return (text + '…');
} else if (item_length == original) {
return text;
}
}
$(document).ready(function() {
var d = new Date();
var s = d.getTime();
$('.service_link').each(function(){
var item_text = $(this).text();
var original_length = item_text.length;
var constrained = constrain(item_text, original_length, 175, 0);
$(this).html(constrained);
});
var e = d.getTime()
alert('Time Taken: ' + ((e - s)/1000));
});
Basically on the first run, it works out how many lowercase i's and how many uppercase Ms fit in the space, and then restricts the text length to that, this reduces the number of iterations massively.
Hope this helps.

Related

How to make .replace script "digit-case-sensitive"?

I have a simple side-project here to help me at work. What I have is a script that will replace a specified number with another.
My problem now though is, I cannot find a way to make it "digit-case-sensitive" (I'm not sure what it's called sorry), meaning, if I want to change the following, they replace only the specified and not anything else. For example:
10 = 80
1 = 75
0 = 65
The problem is, if I replace 10, there's a tendency that it will become 865.
It's changing 10 to 80 first and then the 0 to 65.
Now I really need help as to how do I make the replace script to the specified digit only and not cut the digits or take only half and change them.
Also, how can I make it so that it changes only once for 1 click of button? In this case, it's processing it twice with 1 click of button. It changes 10 to 80 first and then the 0 to 65. What I'd like is run the script only once per click. In this flawed script, it should only be 65 and not process the 0 to 65, since doing so should take 2 clicks.
Here's my sample code, there will be thousands of digits to replace once I move on from this obstacle.
function fixTextarea(textarea) {
textarea.value = textarea.value.replace("", "")
.replaceAll("10", "80")
.replaceAll("1", "75")
.replaceAll("0", "65")
};
function fixtext() {
let textarea = document.getElementById("textarea1");
textarea.select();
fixTextarea(textarea);
}
window.addEventListener('DOMContentLoaded', function(e) {
var area = document.getElementById("textarea1");
var getCount = function(str, search) {
return str.split(search).length - 1;
};
var replace = function(search, replaceWith) {
if (typeof(search) == "object") {
area.value = area.value.replace(search, replaceWith);
return;
}
if (area.value.indexOf(search) >= 0) {
var start = area.selectionStart;
var end = area.selectionEnd;
var textBefore = area.value.substr(0, end);
var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
area.value = area.value.replace(search, replaceWith);
area.selectionStart = start + lengthDiff;
area.selectionEnd = end + lengthDiff;
}
};
});
<textarea id="textarea1" name="textarea1">10</textarea>
<button onclick="fixtext()">Update</button>
I apologize in advance for not being able to make myself too clear.
You could replace with searching for alternative strings and take the longest first.
For prevent changing the value again on a click, store the orginal value to a data-* attribute.
const
replace = s => s.replace(/10|1|0/g, s => ({ 10: '80', 1: '75', 0: '65' }[s]));
console.log(replace('1010'));
console.log(replace('01'));
You'll have to be a little creative, by changing "10" to something that has special meaning so that the match on "0" won't change it, then change it to your end result:
function fixTextarea(textarea) {
textarea.value = textarea.value.replace("", "")
.replaceAll("10", "xx")
.replaceAll("1", "75")
.replaceAll("0", "65")
.replaceAll("xx", "80")
};
You can do the replace in an if else if else block
function fixTextarea(textarea) {
if(textarea.value === "10"){
textarea.value = textarea.value.replace("", "").replaceAll("10", "80")
}else if(textarea.value === "1"){
textarea.value = textarea.value.replace("", "").replaceAll("1", "75")
}else{
textarea.value = textarea.value.replace("", "").replaceAll("0", "65")
}
};
function fixtext() {
let textarea = document.getElementById("textarea1");
textarea.select();
fixTextarea(textarea);
}
window.addEventListener('DOMContentLoaded', function(e) {
var area = document.getElementById("textarea1");
var getCount = function(str, search) {
return str.split(search).length - 1;
};
var replace = function(search, replaceWith) {
if (typeof(search) == "object") {
area.value = area.value.replace(search, replaceWith);
return;
}
if (area.value.indexOf(search) >= 0) {
var start = area.selectionStart;
var end = area.selectionEnd;
var textBefore = area.value.substr(0, end);
var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
area.value = area.value.replace(search, replaceWith);
area.selectionStart = start + lengthDiff;
area.selectionEnd = end + lengthDiff;
}
};
});
<textarea id="textarea1" name="textarea1">10</textarea>
<button onclick="fixtext()">Update</button>

Write/delete text by character

I try to make change of any text by char by char (show text by char, delete text by char and show another one char by char).
What I actually have?
var i = 0;
var terms = ['text <b>bold</b>', 'longer text <b>bold</b>', '<b>bold</b> text 3'];
var timer = setInterval(function() {
var el = $('#el');
var wr = $('#wr');
setInterval(function() {
var str = el.html(); // doesn't work (still shows all content, not sliced one)
el.html(str.substring(0, str.length - 1));
}, 300 / str.length); // (300 / str.length) - do all animation in 300s
i++;
if (i === 3) {
i = 0;
}
}, 2500);
I have problem with slicing last char, so I don't get to adding new text so far :-(
One of variants I tried:
...
var text = terms[i].split('');
setInterval(function() {
el.html(text); // add sliced text in loop... not working as expected
// ...
text = text.slice(0, -1); // slice text by last character
}, 300 / text.length);
Okay, due to the comments a little bit explanation
I have an element
<span id=el>text <b>bold</b></span>
In 300ms interval I need to remove this text char by char.
<span id=el>text <b>bold</b></span>
<span id=el>text <b>bol</b></span>
<span id=el>text <b>bo</b></span>
<span id=el>text <b>b</b></span>
<span id=el>text <b></b></span> // remove 'b'
<span id=el>text</span> // remove ' ' and empty bold
<span id=el>tex</span>
<span id=el>te</span>
<span id=el>t</span>
<span id=el></span>
// now element is empty, since start it's 300ms
// and now I need to put there new text, char by char (whole phrase 300ms again)
<span id=el>l</span>
<span id=el>lo</span>
<span id=el>lon</span>
...
<span id=el>longer tex</span>
<span id=el>longer text</span>
<span id=el>longer text </span> // add space
<span id=el>longer text <b>b</b></span> // add 'b' into bold
<span id=el>longer text <b>bo</b></span>
<span id=el>longer text <b>bol</b></span>
<span id=el>longer text <b>bold</b></span>
// after 2500ms remove this char by char again and replace by third. Etc.
Etc. Can tou help me with that please? Tried that for last 2 days, many attempts, no result...
Thanks
This is how I would organize my code to shrink and grow an element. The only sensible way I can do this is to first replace < and > by the corresponding entity codes < and > so that these characters are not interpreted as actual tags. These 4-letter entity codes will be removed and added as a single unit. In this way you can shrink the string one quasi-character at a time from right to left and still have valid HTML at all times.
The Promise api (well, acually jQuery's $.Deferred version of this) is used to be able to know in a deterministic fashion when the shrink-grow cycle, which is an asynchronous process, has completed to then start the 2500 ms delay (which is another asynchronous process) before beginning anew.
$(function() {
function shrink_grow(resolve, term)
{
term = term.replace(/</g, '<').replace(/>/g, '>');
let el = $('#el');
el.html(term);
let interval = setInterval(shrinker, 30);
function shrinker()
{
let str = el.html();
let n = str.length >= 4 && (str.endsWith('>') || str.endsWith(`<`)) ? 4 : 1;
el.html(str.substr(0, str.length - n));
if (str.length === 0) {
clearInterval(interval);
interval = setInterval(grower, 30);
}
}
function grower()
{
let str = el.html();
if (str.length == term.length) {
clearInterval(interval);
resolve(undefined); // we are done
}
else if (str.length <= term.length - 4 && (term.substr(str.length + 1, 4) == '<' || term.substr(str.length + 1, 4) == '>')) {
el.html(term.substr(0, str.length + 4));
}
else {
el.html(term.substr(0, str.length + 1));
}
}
}
function pause(milliseconds)
{
// Create a new Deferred object
var deferred = $.Deferred();
// Resolve the Deferred after the amount of time specified by milliseconds
setTimeout(deferred.resolve, milliseconds);
return deferred.promise();
}
let terms = ['text <b>bold</b>', 'longer text <i>italic</i> text', '<b>bold</b> text 3'];
let term_number = 0;
let deferred = $.Deferred();
let promise = deferred.promise();
shrink_grow(deferred.resolve, terms[term_number++]);
promise.then(function() {
pause(2500).then(function() {
let deferred = $.Deferred();
let promise = deferred.promise();
shrink_grow(deferred.resolve, terms[term_number++]);
promise.then(function() {
pause(2500).then(function() {
let deferred = $.Deferred();
let promise = deferred.promise();
shrink_grow(deferred.resolve, terms[term_number++]);
promise.then(function() {
console.log('done');
});
});
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="el"></span>
And Keeping the tags intact
This is very complicated, however:
$(function() {
let TOTAL_TIME = 300;
function shrink_grow(resolve, term)
{
let el = $('#el');
let matches = term.match(/<([^>])+>(.*?)<\/\1>/); // look for internal tag
let internalTagTextLength = matches ? matches[2].length : 0;
let internalTagText = internalTagTextLength ? matches[2] : '';
let strlen = term.length;
if (matches) {
strlen -= matches[1].length * 2 + 5;
}
let shrinkGrowInterval = TOTAL_TIME / strlen;
if (shrinkGrowInterval < 16) {
shrinkGrowInterval = 16;
}
let interval = setInterval(grower, shrinkGrowInterval);
function shrinker()
{
let str = el.html();
let matches = str.match(/<([^>])+>(.*?)<\/\1>$/); // <i>text</i> at end of string, for example
if (matches) {
let str2 = matches[2];
if (str2.length < 2) { // get rid of entire tag
str2 = matches[0];
let n = str2.length;
let l = str.length - n;
el.html(str.substr(0, l));
if (l === 0) {
clearInterval(interval);
resolve(undefined); // we are done
}
}
else {
let str2a = str2.substr(0, str2.length - 1);
str = str.replace(/<([^>])+>(.*?)<\/\1>$/, '<' + matches[1] + '>' + str2a + '</' + matches[1] + '>');
el.html(str);
}
}
else {
el.html(str.substr(0, str.length - 1));
if (str.length === 0) {
clearInterval(interval);
resolve(undefined); // we are done
}
}
}
function grower()
{
let str = el.html();
if (str.length == term.length) {
clearInterval(interval);
interval = setInterval(shrinker, shrinkGrowInterval);
}
else {
let matches = term.substr(str.length).match(/^<([^>])+>(.*?)<\/\1>/); // start of <i>text</i>, for example?
if (matches) {
let str2 = '<' + matches[1] + '>' + matches[2].substr(0, 1) + '</' + matches[1] + '>';
el.html(str + str2);
}
else {
let matches = str.match(/<([^>])+>(.*?)<\/\1>$/); // <i>text</i> at end of string, for example
if (matches) {
let str2 = matches[2];
let l = str2.length;
if (l == internalTagTextLength) {
el.html(term.substr(0, str.length + 1));
}
else {
let str2a = internalTagText.substr(0, l + 1);
str = str.replace(/<([^>])+>(.*?)<\/\1>$/, '<' + matches[1] + '>' + str2a + '</' + matches[1] + '>');
el.html(str);
}
}
else {
el.html(term.substr(0, str.length + 1));
}
}
}
}
}
let terms = ['text <b>bold</b>', 'longer text <i>italic</i> text', '<b>bold</b> text 3'];
let nTerms = terms.length;
let termNumber = -1;
function callShrinkGrow()
{
if (++termNumber >= nTerms) {
termNumber = 0;
}
let deferred = $.Deferred();
let promise = deferred.promise();
shrink_grow(deferred.resolve, terms[termNumber]);
promise.then(callShrinkGrow);
}
callShrinkGrow();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<span id="el"></span>
Okay according to my understanding, you want to show string/text char by char. So I think this will help you.
var str = "Hello World";
var c = "";
var i = 0;
(function loop(){
if (i++ > str.length-1) return;
c = c + str[i-1];
setTimeout(function(){
$("#charP").text(c);
loop();
}, 100);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p id="charP"></p>
</div>

Logic for returning caret position for changed input

I'll be thankful for feedback on how i should build a logic of returning caret position for modified input.
Case: we have an input, processed by JS to be formatted like x999y999z9999, where x,y,z - are dividers we define on case by case basis. We process and modify it as intended, but i seem to become lost in logic for returning user's caret position in context of those x,y&z of variable length. I'm even kinda inclined to build a whole complex of if\else in response to those length fluctuations, but there probably is a simpler solution, which i'm missing.
Thanks in advance!
Code example: https://jsfiddle.net/zktva4kc/
function doGetCaretPosition (field) {
if (!!field){
var CaretPos = 0;
// IE Support
if (document.selection) {
field.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -field.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (field.selectionStart || field.selectionStart == '0')
CaretPos = field.selectionStart;
return (CaretPos);
}else{
console.log("No such field exist here for function initiation.");
}
}
function setCaretPosition(field, pos)
{
if (!!field){
if(field.setSelectionRange)
{
field.focus();
field.setSelectionRange(pos,pos);
}
else if (field.createTextRange) {
var range = field.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}else{
console.log("No such field exist here for function initiation.");
}
}
function formatItDown(field, format) {
if (!!field){
field.oninput = function () {
var position=doGetCaretPosition(field);
var sInput=this.value;
var input = this.value;
input = input.replace(/[^\d]/gi, "");
var first = input.substr(0, 3);
var second = input.substr(3, 3);
var third = input.substr(6, 4);
if (input.length > 3) {
first = format[0] + first + format[1];
}
if (input.length > 6) {
second = second + format[2];
}
formatted = first + second + third;
//x012y456z8901
/* this here is the problem area when we use some complex formats
if ((formatted[3]!=sInput[3])&&(position>3)&&(position<6)){
position=position+1;
}else if ((formatted[7]!=sInput[7])&&(position>7)){
position=position+1;
}*/
this.value = formatted;
setCaretPosition(field, position);
}
}else{
console.log("No such field exist here for function initiation.");
}
}
formatItDown(document.getElementById('exampleInput'), ["--","==","__"]);
<input id='exampleInput'>
Why not quickly google for something well coded and bug free ?
Here is a good plugin I used once
https://github.com/acdvorak/jquery.caret

Angularjs ng-bind-html with custom Filter

I am currently working with ng-bind-html. Basically, what I am trying to do is, when I post a blog, the blog contains links and other styling. So when I am trying to show the list of blogs, I am using ng-bing-html like this:
<p ng-bind-html="blog.blogContent"></p>
which works fine.
But in addition, I try to truncate the blog and show only few paragraphs with view more option by passing a custom filter. But when I pass the filter I get the following:
<p ng-bind-html="blog.blogContent | Truncate"></p>
Error: [$sanitize:badparse] The sanitizer was unable to parse the
following block of html: <a href="https:.......
My Filter looks like this:
return function (text, length, end) {
if (text !== undefined) {
if (isNaN(length)) {
length = 450;
}
if (end === undefined) {
end = ".......";
}
if (text.length <= length || text.length - end.length <= length) {
return text;
} else {
return String(text).substring(0, length - end.length) + end;
}
}
You can solve this using custom directives and filters. try this one: https://stackoverflow.com/a/45076560/6816707
I used the solution posted by Minouris in this post (Javascript truncate HTML text) and adapted it into an AngularJS filter. It seems to work pretty well. The filter is
angular.module('plunker').filter('Truncate', function() {
return function(text, length, end) {
if (text !== undefined) {
if (isNaN(length)) {
length = 20;
}
if (end === undefined) {
end = ".......";
}
if (text.length <= length || text.length - end.length <= length) {
return text;
}
var truncated = text.substring(0, length);
// Remove line breaks and surrounding whitespace
truncated = truncated.replace(/(\r\n|\n|\r)/gm,"").trim();
// If the text ends with an incomplete start tag, trim it off
truncated = truncated.replace(/<(\w*)(?:(?:\s\w+(?:={0,1}(["']{0,1})\w*\2{0,1})))*$/g, '');
// If the text ends with a truncated end tag, fix it.
var truncatedEndTagExpr = /<\/((?:\w*))$/g;
var truncatedEndTagMatch = truncatedEndTagExpr.exec(truncated);
if (truncatedEndTagMatch != null) {
var truncatedEndTag = truncatedEndTagMatch[1];
// Check to see if there's an identifiable tag in the end tag
if (truncatedEndTag.length > 0) {
// If so, find the start tag, and close it
var startTagExpr = new RegExp(
"<(" + truncatedEndTag + "\\w?)(?:(?:\\s\\w+(?:=([\"\'])\\w*\\2)))*>");
var testString = truncated;
var startTagMatch = startTagExpr.exec(testString);
var startTag = null;
while (startTagMatch != null) {
startTag = startTagMatch[1];
testString = testString.replace(startTagExpr, '');
startTagMatch = startTagExpr.exec(testString);
}
if (startTag != null) {
truncated = truncated.replace(truncatedEndTagExpr, '</' + startTag + '>');
}
} else {
// Otherwise, cull off the broken end tag
truncated = truncated.replace(truncatedEndTagExpr, '');
}
}
// Now the tricky part. Reverse the text, and look for opening tags. For each opening tag,
// check to see that he closing tag before it is for that tag. If not, append a closing tag.
var testString = reverseHtml(truncated);
var reverseTagOpenExpr = /<(?:(["'])\w*\1=\w+ )*(\w*)>/;
var tagMatch = reverseTagOpenExpr.exec(testString);
while (tagMatch != null) {
var tag = tagMatch[0];
var tagName = tagMatch[2];
var startPos = tagMatch.index;
var endPos = startPos + tag.length;
var fragment = testString.substring(0, endPos);
// Test to see if an end tag is found in the fragment. If not, append one to the end
// of the truncated HTML, thus closing the last unclosed tag
if (!new RegExp("<" + tagName + "\/>").test(fragment)) {
truncated += '</' + reverseHtml(tagName) + '>';
}
// Get rid of the already tested fragment
testString = testString.replace(fragment, '');
// Get another tag to test
tagMatch = reverseTagOpenExpr.exec(testString);
}
return truncated;
}
}
function reverseHtml(str) {
var ph = String.fromCharCode(206);
var result = str.split('').reverse().join('');
while (result.indexOf('<') > -1) {
result = result.replace('<',ph);
}
while (result.indexOf('>') > -1) {
result = result.replace('>', '<');
}
while (result.indexOf(ph) > -1) {
result = result.replace(ph, '>');
}
return result;
}
});
Working plunkr:
http://plnkr.co/edit/oCwmGyBXB26omocT2q9m?p=preview
I havent tested the above solution and you may run into issues with more complicated HTML strings. May I suggest using a Jquery library like https://github.com/pathable/truncate to be safe?

jQuery password generator

I have the following JS code that checks a password strength and also creates a random password as well. What I want to do is edit the code so that instead of putting the generated password inside the password field it will put it inside a span tag with say an id of randompassword. In addition that I would like it so that by default there will be a random password inside the span tag and then when the user clicks the button it will generate another one. And also move the link to be next to span tag rather than the password box.
Thanks.
Here is the code:
$.fn.passwordStrength = function( options ){
return this.each(function(){
var that = this;that.opts = {};
that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);
that.div = $(that.opts.targetDiv);
that.defaultClass = that.div.attr('class');
that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;
v = $(this)
.keyup(function(){
if( typeof el == "undefined" )
this.el = $(this);
var s = getPasswordStrength (this.value);
var p = this.percents;
var t = Math.floor( s / p );
if( 100 <= s )
t = this.opts.classes.length - 1;
this.div
.removeAttr('class')
.addClass( this.defaultClass )
.addClass( this.opts.classes[ t ] );
})
.after('Generate Password')
.next()
.click(function(){
$(this).prev().val( randomPassword() ).trigger('keyup');
return false;
});
});
function getPasswordStrength(H){
var D=(H.length);
if(D>5){
D=5
}
var F=H.replace(/[0-9]/g,"");
var G=(H.length-F.length);
if(G>3){G=3}
var A=H.replace(/\W/g,"");
var C=(H.length-A.length);
if(C>3){C=3}
var B=H.replace(/[A-Z]/g,"");
var I=(H.length-B.length);
if(I>3){I=3}
var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
if(E<0){E=0}
if(E>100){E=100}
return E
}
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$_+?%^&)";
var size = 10;
var i = 1;
var ret = ""
while ( i <= size ) {
$max = chars.length-1;
$num = Math.floor(Math.random()*$max);
$temp = chars.substr($num, 1);
ret += $temp;
i++;
}
return ret;
}
};
$(document)
.ready(function(){
$('#password1').passwordStrength({targetDiv: '#iSM',classes : Array('weak','medium','strong')});
});
// you can use another improved version to generate password as follows
//Define
function wpiGenerateRandomNumber(length) {
var i = 0;
var numkey = "";
var randomNumber;
while( i < length) {
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=90)) { continue; }
if ((randomNumber >=91) && (randomNumber <=122)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
i++;
numkey += String.fromCharCode(randomNumber);
}
return numkey;
}
// Call
var myKey=wpiGenerateRandomNumber(10); // 10=length
alert(myKey);
// Output
2606923083
This line:
$(this).prev().val( randomPassword() ).trigger('keyup');
is inserting the value after a click. So you can change that value to stick the password wherever you want it. For example you could change it to:
$('span#randompassword').html(randomPassword());
You could also run this when the page loads to stick something in that span right away:
$(document).ready(function(){
$('span#randompassword').html(randomPassword());
});
//Very simple method to generate random number; can be use to generate random password key as well
jq(document).ready( function() {
jq("#genCodeLnk").click( function() {
d = new Date();
t = d.getTime();
jq("#cstm_invitecode").val(t);
});
});

Categories