Displaying Password Meter Strength Level - javascript

enter code here
function passwordScore(password)
var score = 0;
if (!pass)
return score;
//
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
//Checking the variations that have been entered in the password meter.
var variations = {
Digitals: /\d/.test(pass),
LowerCaseLetters: /[a-z]/.test(pass),
UpperCaseLetters: /[A-Z]/.test(pass),
NonSpaceWords: /\W/.test(pass),
}
varitationCount = 0;
for (var check in varitations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
//Checking the password strength score with the name of the strength level.
function checkPasswordStrength(pass) {
var score = passwordScore(pass);
if (score > 80)
return "Very Strong";
if (score > 60)
return "Strong";
if (score > 40)
return "Good";
if (score > 20)
return "Weak";
if (score > 0)
return "Very Weak";
return "";
}
/* The font type, background colour and the margin settings for the body tag*/
body {
font-family: "Calibri (Body)";
background-color: #006699;
margin: 0;
}
/* The font size, padding, margin, text align and background colour settings for the h1 tag*/
h1 {
font-size: 30px;
padding: 0;
margin: 0;
text-align: center;
background-color: #cccc99;
}
/* The padding, width and the margin settings for the div tag*/
div {
padding: 10px;
width: 600px;
margin: 0 auto;
}
/* The width settings for the myInput function*/
#myInput {
width: 100%;
}
.Strength{
display: inline-block;
}
<!DOCTYPE html>
<html lang="en-gb">
<head>
<meta charset="utf-8" />
<title>Password Meter</title>
<!--The CSS link tag for the StyleSheet.css file.-->
<link type="text/css" href="./StyleSheet.css" rel="stylesheet" />
<!--The script tag for HideorDisplay.js file.-->
<script src="HideorDisplay.js"></script>
<!--The script tag for PasswordMeter.js file.-->
<script src="PasswordMeter.js"></script>
<!--The script tag for PasswordStrengthLevel.js file.-->
<script src="PasswordStrengthLevel.js"></script>
<!--The script tag for Suggestions.js file.-->
<script src="Suggestions.js"></script>
<!--The script tag for PasswordIntegrity.js file.-->
<script src="PasswordIntegrityFacts.js"></script>
</head>
<body>
<!--The Password Meter header tag.-->
<h1> Password Meter</h1>
<div>
<input type="password" id="myInput" class="input_1, Password" onkeyup="checkPasswordStrength()"><br><br>
<div class="Strength" id="StrengthLevel" text="Strength Level"></div>
<div class="Strength" id="StrengthScore" text="Strength Score (0)"></div>
<input type="checkbox" onclick="passwordVisible()"> Hidden or Visible
</div>
</body>
</html>
I am currently creating password strength meters in visual studio in ASP.net. The main page is html linking to style sheets and JavaScript files.
The strength level code is coded in JavaScript linked to a HTML page. The requirements of the strength level along with the score is
0 = very weak, 20 = weak, 40 = good, 60 = strong and 80 = very strong.
Currently I am having problems getting the strength level to appear when the program is running because when I am typing the password, nothing is appearing. I don't know how to resolve this.
I have tried to link to the div class id but nothing is happening.
I have looked at a few examples that are written in JavaScript but they are complex to understand.
*Can anyone please provide suggestions into resolving this problem or provide a example into structuring the code and linking the function to HTML page?

$("input").on("keyup",function(){
var pass = $(this).val();
var strength = 1;
var arr = [/.{5,}/, /[a-z]+/, /[0-9]+/, /[A-Z]+/];
jQuery.map(arr, function(regexp) {
if(pass.match(regexp))
strength++;
});
console.log(strength==1?"very Weak":strength==2?"Weak":strength==3?"medium":strength==4?"good":"very good");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

Add an id called password to the input tag and remove the inline event handler eg.
<input type="password" id="password" class="input_1 Password"><div>
Made a few slight changes to the Password Meter js file
function scorePassword(pass) {
var score = 0;
if (!pass) {
return score;
}
var letters = {};
for (var i = 0; i < pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
var variations = {
digitals: /\d/.test(pass),
lowerCaseLetters: /[a-z]/.test(pass),
upperCaseLetters: /[A-Z]/.test(pass),
nonSpaceWords: /\W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80) {
return "Very Strong";
} else if (score > 60) {
return "Strong";
} else if (score > 40) {
return "Good";
} else if (score > 20) {
return "Weak";
} else if (score <= 10) {
return "Very Weak";
} else {
return "";
}
}
Add another function to the Password Meter js file to display the values from above.
var password = document.getElementById("password");
password.onkeyup = function () {
var pass = this.value;
var strengthLevel = document.getElementById("StrengthLevel");
var strengthScore = document.getElementById("StrengthScore");
strengthLevel.innerHTML = checkPassStrength(pass);
strengthScore.innerHTML = scorePassword(pass);
}
To toggle the input element (toggle password visibility) add an id called passwordVisibility to the checkbox then add another function to the Password Meter js file
var passwordVisibility = document.getElementById("passwordVisibility");
passwordVisibility.onclick = function() {
var togglePasswordVisibility = document.getElementById("password");
if (togglePasswordVisibility.type === "password") {
togglePasswordVisibility.type = "text";
} else {
togglePasswordVisibility.type = "password";
}
}

Related

JavaScript doesn't display as intended on HTML Site

I am building an example in a book trying to learn JavaScript but for some reason it doesn't look like it reading the JS file when I run the html. What am I missing? The HTML and CSS shows up just fine, but when I try to enter new values its doesn't do anything. Its seems like its not reading the JS file. They are all in the same directory as well when ran.
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var n = 4;
var size = 10;
var $ = function(id) {
return document.getElementById(id);
};
function addScore() {
var name = $('name').value;
var score = $('score').value;
if (name == "" || score == "" || isNaN(score)) alert("Invalid data ");
else if (n < size) {
names[n] = name;
scores[n] = score;
n++;
} else alert("Array already full");
}
function displayResults() {
var h, avg, name;
h = scores[0];
name = names[0];
avg = 0;
for (z = 0; z < n; z++) {
if (h > scores[0]) {
h = scores[z];
name = names[z]
}
avg = avg + scores[z];
}
avg = avg / n;
var con = "<B>Results </b><br> Average Score= " + avg + "<br>Highest Score = " + name + " with a score of " + h;
$('results').innerHTML = con;
}
function displayScores() {
var con = "<tr><td colspan='2'><h2>Scores</h2></td></tr><tr><td>Name</td><td>Score</td></tr> ";
for (z = 0; z < n; z++) {
con = con + "<tr><td>" + names[z] + "</td><td>" + scores[z] + "</td></tr>"
}
$('scores_table').innerHTML = con;
}
window.onload = function() {
$("add").onclick = addScore;
$("display_results").onclick = displayResults;
$("display_scores").onclick = displayScores;
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
padding: 10px 20px;
width: 600px;
border: 3px solid blue;
}
h1 {
color: blue;
margin-top: 0;
margin-bottom: .5em;
}
h2 {
color: blue;
font-size: 120%;
padding: 0;
margin-bottom: .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 3em;
text-align: right;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
p {
margin: 0;
}
td {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Score Array</title>
<link rel="stylesheet" href="styles.css" />
<script src="test_scores.js"></script>
</head>
<body>
<main>
<h1>Use a Test Score array</h1>
<label for="name">Name:</label>
<input type="text" id="name"><br>
<label for="score">Score:</label>
<input type="text" id="score"><br>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_results" value="Display Results">
<input type="button" id="display_scores" value="Display Scores"><br>
<div id="results"></div>
<table id="scores_table"></table>
</main>
</body>
</html>
Expected Outcome:
EDIT:
Upon closer inspection and learning about the exception message you're getting, you seem to be using jQuery and those jQuery selectors don't seem to be targeting valid html elements.
You need to make sure you're including the jQuery library (which you appear not to be doing) and that you're using the right syntax in your jQuery selectors, such as using $('#add') instead of $('add') and that elements have the corresponding Id associated to them. You have several problems like this in your code.
If you really want to use jQuery just add the '#' symbol before the name of each jQuery selector. I've modified the code. Upload the updated JS to your js file (without the start and close tag) and try again.
I suggest you don't use jQuery just now and replace the jQuery selector for vanilla JS (pure JS). For that, instead replace every instance of $('...') with document.getElementById('...'), where ... is the name of your element's ID attribute.
Original answer:
With the provided information it's not possible to determine what the issue is. But you could try different things to find out.
If you're using Google Chrome browser. Google dev tools is a mandatory tool to troubleshoot, test and track your code in-browser. You can find an intro to Google Chrome Dev Tools here.
I suspect that your JS file is either not called test_scores.js or is not in the same location as your HTML file.
To test this, I suggest you try loading your JS directly in your HTML file. To achieve that just replace the line in your HTML file:
<script src="test_scores.js"></script>
with the following:
<script>
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var n = 4;
var size = 10;
var $ = function(id) {
return document.getElementById(id);
};
function addScore() {
var name = $('#name').value;
var score = $('#score').value;
if (name == "" || score == "" || isNaN(score)) alert("Invalid data ");
else if (n < size) {
names[n] = name;
scores[n] = score;
n++;
} else alert("Array already full");
}
function displayResults() {
var h, avg, name;
h = scores[0];
name = names[0];
avg = 0;
for (z = 0; z < n; z++) {
if (h > scores[0]) {
h = scores[z];
name = names[z]
}
avg = avg + scores[z];
}
avg = avg / n;
var con = "<B>Results </b><br> Average Score= " + avg + "<br>Highest Score = " + name + " with a score of " + h;
$('#results').innerHTML = con;
}
function displayScores() {
var con = "<tr><td colspan='2'><h2>Scores</h2></td></tr><tr><td>Name</td><td>Score</td></tr> ";
for (z = 0; z < n; z++) {
con = con + "<tr><td>" + names[z] + "</td><td>" + scores[z] + "</td></tr>"
}
$('#scores_table').innerHTML = con;
}
window.onload = function() {
$("#add").onclick = addScore;
$("#display_results").onclick = displayResults;
$("#display_scores").onclick = displayScores;
};
</script>
If this doesn't solve it. Another issue could be that you're getting a cached version of your application. Try hard reloading your page (clear cache and reload) and see if that makes a difference.

How to make a barcode smaller in HTML for printing on one page?

So I am having trouble making my bar codes smaller to fit on one page.
There are supposed to be 3 bar codes per row and when I view it on the screen it looks fine.However, when I go to preview how it will look when it prints they get stuck together.If I make their width too small they no longer scan.
So, how do I make them smaller to fit on one page while they are still able to be scanned?
I have included the main part of my code below it is an HTML file but includes both HTML and JavaScript. I can't put the JavaScript in another file and have it as a source because everything has to be in one file. Any help is appreciated!
<body>
<div width = 100%>
<table class="no-spacing" cellspacing="0">
<tr>
<td width = 25%>
<div id="barcodecontainer" style="width:125%">
<div id="inputdata" >123456123</div> <!-- Enter the NIIN for the barcode here -->
Description : Code128A<br /><!-- Enter the description for the barcode here-->
</div></div>
</td><br/>
<td width = 25%>
<div id="barcodecontainer" style="width:125%">
<div id="inputdata1" >456789123</div> <!-- Enter the NIIN for the barcode here -->
Description : Code128A<br /><!-- Enter the description for the barcode here-->
</div>
</div>
</td>
<td width = 25%>
<div id="barcodecontainer" style="width:125%">
<div id="inputdata2" >111111123</div> <!-- Enter the NIIN for the barcode here -->
Description : Code128A<br /><!-- Enter the description for the barcode here-->
</div>
</div>
</td>
</tr>
</table>
<script type="text/javascript">
/* <![CDATA[ */
function get_object(id) {
var object = null;
if (document.layers) {
object = document.layers[id];
} else if (document.all) {
object = document.all[id];
} else if (document.getElementById) {
object = document.getElementById(id);
}
return object;
get_object("inputdata").innerHTML=DrawHTMLBarcode_Code128A(get_object("inputdata").innerHTML,"yes","in",0,2.5,.6,"bottom","center","","black","white");
get_object("inputdata1").innerHTML=DrawHTMLBarcode_Code128A(get_object("inputdata1").innerHTML,"yes","in",0,2.3,.6,"bottom","center","","black","white");
get_object("inputdata2").innerHTML=DrawHTMLBarcode_Code128A(get_object("inputdata2").innerHTML,"yes","in",0,2.4,.6,"bottom","center","","black","white"</script>
Not sure if this will be any help, but I use CSS to control label size and page formatting.
<!doctype html>
<html lang="en">
<head>
<title>Plain Vanilla JS Code 128B Barcodes</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css">
<!- CSS adapted from article: boulderinformationservices.wordpress.com/2011/08/25/print-avery-labels-using-css-and-html/ ->
body {
margin-top: 0in;
margin-left: 0in;
}
.page {
width: 8.5in;
height: 10.5in;
margin-top: 0.5in;
margin-left: 0.25in;
}
.label {
width: 2.1in;
height: .9in;
padding: .125in .3in 0;
margin-right: 0.125in;
float: left;
text-align: center;
overflow: hidden;
}
.page-break {
clear: left;
display:block;
page-break-after:always;
}
</style>
</head>
<body>
<div id="result"></div>
<script type="text/javascript">
// The MIT License (MIT)
// Copyright (c) 2017, Notionovus, LLC.
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
var arrayCode128Bin = [ '11011001100', '11001101100', '11001100110', '10010011000', '10010001100', '10001001100', '10011001000', '10011000100', '10001100100', '11001001000', '11001000100', '11000100100', '10110011100', '10011011100', '10011001110', '10111001100', '10011101100', '10011100110', '11001110010', '11001011100', '11001001110', '11011100100', '11001110100', '11101101110', '11101001100', '11100101100', '11100100110', '11101100100', '11100110100', '11100110010', '11011011000', '11011000110', '11000110110', '10100011000', '10001011000', '10001000110', '10110001000', '10001101000', '10001100010', '11010001000', '11000101000', '11000100010', '10110111000', '10110001110', '10001101110', '10111011000', '10111000110', '10001110110', '11101110110', '11010001110', '11000101110', '11011101000', '11011100010', '11011101110', '11101011000', '11101000110', '11100010110', '11101101000', '11101100010', '11100011010', '11101111010', '11001000010', '11110001010', '10100110000', '10100001100', '10010110000', '10010000110', '10000101100', '10000100110', '10110010000', '10110000100', '10011010000', '10011000010', '10000110100', '10000110010', '11000010010', '11001010000', '11110111010', '11000010100', '10001111010', '10100111100', '10010111100', '10010011110', '10111100100', '10011110100', '10011110010', '11110100100', '11110010100', '11110010010', '11011011110', '11011110110', '11110110110', '10101111000', '10100011110', '10001011110', '10111101000', '10111100010', '11110101000', '11110100010', '10111011110', '10111101110', '11101011110', '11110101110', '11010000100', '11010010000', '11010011100', '1100011101011', '11010111000'];
var array5bit_A = [ 'f//AAAAAAAAAAAAAAAAAAAA', 'f//AAAAAAAAAAAAAAAAAAAB', 'f//AAAAAAAAAAAAAAEAAAD/', 'f//AAAAAAAAAAAAAAEAAAAA', 'f//AAAAAAAAAQAAAP8AAAAA', 'f//AAAAAAAAAQAAAP8AAAAB', 'f//AAAAAAAAAQAAAAAAAAD/', 'f//AAAAAAAAAQAAAAAAAAAA', 'f//AAABAAAA/wAAAAAAAAAA', 'f//AAABAAAA/wAAAAAAAAAB', 'f//AAABAAAA/wAAAAEAAAD/', 'f//AAABAAAA/wAAAAEAAAAA', 'f//AAABAAAAAAAAAP8AAAAA', 'f//AAABAAAAAAAAAP8AAAAB', 'f//AAABAAAAAAAAAAAAAAD/', 'f//AAABAAAAAAAAAAAAAAAA', 'QD/AAD/AAAAAAAAAAAAAAAA', 'QD/AAD/AAAAAAAAAAAAAAAB', 'QD/AAD/AAAAAAAAAAEAAAD/', 'QD/AAD/AAAAAAAAAAEAAAAA', 'QD/AAD/AAAAAQAAAP8AAAAA', 'QD/AAD/AAAAAQAAAP8AAAAB', 'QD/AAD/AAAAAQAAAAAAAAD/', 'QD/AAD/AAAAAQAAAAAAAAAA', 'QD/AAAAAAAA/wAAAAAAAAAA', 'QD/AAAAAAAA/wAAAAAAAAAB', 'SL/AADeAAAA/gAAAAIAAAD+', 'QD/AAAAAAAA/wAAAAEAAAAA', 'QD/AAAAAAAAAAAAAP8AAAAA', 'QD/AAAAAAAAAAAAAP8AAAAB', 'QD/AAAAAAAAAAAAAAAAAAD/', 'QD/AAAAAAAAAAAAAAAAAAAA'];
var array5bit_B = [ 'US0CAuSD38g', 'UUYCA7QBErs', 'ajEDAm49ReY', 'UUoCA+juogg', 'bjEDAjQrOn0', 'bkoDA3iPVH4', 'ajUDAt82atY', 'UU4CA1nljTg', 'cjEDAghkmFU', 'ckoDA0TA9lY', 'izUEAhrxcbg', 'ck4DAxY8F10', 'bjUDAlvFFR8', 'bk4DAxdhexw', 'ajkDAr7LFAw', 'UVICAyQ+UJI', 'TTECAq7UnEM', 'TUoCA+Jw8kA', 'ZjUDAmZGozo', 'TU4CA7CME0s', 'ajUDAvnk9E4', 'ak4DA7VAmk0', 'ZjkDAtle3bI', 'TVICAxOyzrM', 'STUCAqHeHtM', 'SU4CA+16cNA', 'h6QEAZKdo54', 'SVICA62zYxM', 'RTkCAqx1lb4', 'RVICA/z3WM0', 'QT0CAkdoxRU', 'KFYBA46vJCA'];
var stringStart = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAACCAQAAADLaIVbAAAANUlEQVQIHQEqANX/A';
var stringMid = 'AAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAA';
var stringEnd = 'AAAAASUVORK5CYII=" style="width:';
function genBarcode(inputString, intWidth, intHeight) {
var arraySeq = [], i, intChunks, resultString;
var intRawmod = inputString.length % 5;
for (i = 0; i < 5 - intRawmod; i += 1) {
inputString += "0";
}
intChunks = inputString.length / 5;
for (i = 0; i < intChunks; i += 1) {
arraySeq[i] = parseInt(inputString.substr(i * 5, 5), 2);
}
resultString = "";
for (i = 0; i < arraySeq.length; i += 1) {
resultString += stringStart + array5bit_A[arraySeq[i]] + stringMid + array5bit_B[arraySeq[i]] + stringEnd + intWidth + 'px;height:' + intHeight + 'px;">';
}
return resultString;
}
function funcCode128B(strText) {
var j, intWeight, intWtProd = 0;
var strRaw = "";
var arrayData = [];
arrayData[0] = 104;
intWtProd = 104;
for (j = 0; j < strText.length; j += 1) {
arrayData[j + 1] = strText.charCodeAt(j) - 32;
intWeight = j + 1;
intWtProd += intWeight * arrayData[j + 1];
}
arrayData[j + 1] = intWtProd % 103;
arrayData[j + 2] = 106;
for (j = 0; j < arrayData.length; j += 1) {
strRaw += arrayCode128Bin[arrayData[j]];
}
return(strRaw);
}
function fnNewPage(pageno) {
var strNewPage, startNewPage = '<div class="page" id="page';
strNewPage = startNewPage + pageno + '">';
return strNewPage;
}
function fnEndPage() {
var strEndPage = '<div class="page-break"></div></div>';
return strEndPage;
}
function fnNewLabel(barcode, txtHR) {
var strNewLabel, startNewLabel = '<div class="label">';
strNewLabel = startNewLabel + barcode + '<br>' + txtHR + '</div>';
return strNewLabel;
}
function fnShowPage() {
var outerLoop, innerLoop, indexBarcode, txtHumanReadable, strPage = "";
for (outerLoop = 0; outerLoop < 2; outerLoop += 1) {
strPage += fnNewPage(outerLoop + 1);
for (innerLoop = 0; innerLoop < 30; innerLoop += 1) {
indexBarcode = (30 * outerLoop) + innerLoop + 400;
switch (indexBarcode) {
case 400:
txtHumanReadable = '' + 123456123; break;
case 401:
txtHumanReadable = '' + 456789123; break;
case 402:
txtHumanReadable = '' + 111111123; break;
default:
txtHumanReadable = 'Test1' + indexBarcode;
}
txtBarcode = genBarcode(funcCode128B(txtHumanReadable), 6.5, 34);
strPage += fnNewLabel(txtBarcode, txtHumanReadable)
}
strPage += fnEndPage();
}
document.getElementById("result").innerHTML = strPage;
}
fnShowPage();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</script>
</body>
</html>
In order to prevent the DIVs from getting mixed up, you need to set the width of the divs with id="barcodecontainer" to 100%. This way its content won't get out of its parent <td>.
<div id="barcodecontainer" style="width:100%">
Then just set the width of the "parent" DIVs to whatever percentage of the screen you want, preferable using the style attribute and vw units other than width and %:
<td style="width:20vw">
and not:
<td width = 25%>
In general, I suggest you use CSS instead of repeating the style attributes for each element, especially because your code is already built in hierarchy.
Here's a complete example.
Not to be super critical, but in my opinion you are using out dated web practices.
I recommend not using table and using my little best friend flexbox.
That being said, you are trying to shrink a bar code down without it losing its scan ability.
I would try and make a few divs, then from their flex them into the location you want. From that make them a big or small as you want by resizing the divs.
Hopefully, this helped.
It's hard to come up with a solution without seeing a running demo of the problem you are facing. (https://stackoverflow.com/help/mcve)
(Moreover the script that you have included has some syntax errors as well. Missing closing brackets for function definition as well as on the last line. I assume these are just some typos you made while posting the question here.)
Looking at the API documentation for DrawHTMLBarcode_Code128A # https://www.barcoderesource.com/htmlBarcodeAPI.shtml, I can see that the 4th param is minBarWidth. You have currently set it to 0. Instead you can set it to 2.5, same as the value for width param, and see if that helps.
(You should combine this suggestion with the suggestions given by #GalAbra. Those are also valid points)

Comprobating function not working as it should

I need to create a lottery game. I have an idea of how the whole code should be and it's mostly done, but I have a problem:
I have a button with an onclick called generar(), and this function, needs to draw 3 numbers from 1 to 999 and create along with the three numbers, another button which after pressing it, draws another number and then (the new button) checks the new number number with the ones who are already created to see if I won, or not.
Okay, I've managed to do the whole code, but the comparison of the three first numbers with the fourth number, doesn't work correctly. Always, the comprobation which says if I won or not, writes "¡Perdedor!" (looser!).
This is my code:
<html>
<head>
<title>Práctica 3</title>
<style>
#contenedor { border: 1px black solid;
width: 250px;
height: 250px;
float: left;
margin-right: 5px;
text-align: center;
margin-bottom: 5px; }
</style>
</head>
<body>
<div id="contenedor"> <p id="primerNumero"/> </div>
<div id="contenedor"> <p id="segundoNumero"/> </div>
<div id="contenedor"> <p id="tercerNumero"/> </div>
<button id="generar" onclick="generar()">Genera dècims</button>
<div id="contenedor"> <p id="resultado"/> </div>
<p id="t"/>
<script>
function generar() {
var primerNumero = Math.floor(Math.random() * 10);
var segundoNumero = Math.floor(Math.random() * 10);
var tercerNumero = Math.floor(Math.random() * 10);
var botones = document.getElementsByTagName("BUTTON").length;
if (botones < 2) {
generarBotones();
}
document.getElementById("primerNumero").innerHTML = primerNumero;
document.getElementById("primerNumero").style.fontSize = "72px";
document.getElementById("segundoNumero").innerHTML = segundoNumero;
document.getElementById("segundoNumero").style.fontSize = "72px";
document.getElementById("tercerNumero").innerHTML = tercerNumero;
document.getElementById("tercerNumero").style.fontSize = "72px";
}
function generarBotones() {
var boton = document.createElement("BUTTON");
var t = document.createTextNode("Realizar sorteig");
boton.onclick = function(){
var numeroGanador = Math.floor(Math.random() * 10);
document.getElementById("resultado").innerHTML = numeroGanador;
document.getElementById("resultado").style.fontSize = "72px";
if(primerNumero == numeroGanador || segundoNumero == numeroGanador || tercerNumero == numeroGanador) {
document.getElementById("t").innerHTML = "¡Ganador!";
} else {
document.getElementById("t").innerHTML = "¡Perdedor!";
}
};
boton.appendChild(t);
document.body.appendChild(boton);
}
</script>
</body>
</html>
If somebody can tell me why and where I fail and a possible solution, it will be great. I will very grateful if an explanation is given too
primerNumero
segundoNumero
tercerNumero
Are html elements, not value, to get the value is necessary to use innerText OR innerHTML.
if(primerNumero.innerText == numeroGanador || segundoNumero.innerText == numeroGanador || tercerNumero.innerText == numeroGanador) {
document.getElementById("t").innerHTML = "¡Ganador!";
} else {
document.getElementById("t").innerHTML = "¡Perdedor!";
}
Or you can rename the variables to a different name of the element, because your problem is that the variables that contain the generated numbers are the same name as the id of the html element. If rename will work according to your first code.

How to show a custom message based on the password strength

Hi I have the following piece of code that basically checking the strength of the password and showing a div with colors based on the strength. Like a strength meter. How can I mutate the content of the div based on the strength of the password, like if the password is weak, color change to red and content says "Weak passwrd!!", if the password is moderate then content should be "Moderate password" etc. Also I would like to add a check box in the divs so if the condition is met then the color of the check box shud change to green if not then red. etc.
My codes:
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>My AngularJS App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body ng-controller="stageController">
<form name="myForm" novalidate>
<label for="pw">Type a password</label><br/>
<input type="password" ng-model="pw" name="pw" id="pw" />
<li id="strength" check-strength="pw"></li>
</form>
</body>
CSS:
input.ng-pristine + ul#strength {
display:none;
}
ul#strength {
display:inline;
list-style:none;
margin:0;
margin-left:15px;
padding:0;
vertical-align:2px;
}
.point:last {
margin:0 !important;
}
.point {
background:#DDD;
border-radius:2px;
display:inline-block;
height:5px;
margin-right:1px;
width:20px;
}
#footer {
position:fixed;
bottom:5px;
}
AngularJS:
'use strict';
angular.module('myApp', ['myApp.directives']);
/* Controllers */
function stageController($scope) {
$scope.pw = '';
}
/* Directives */
angular.module('myApp.directives', []).
directive('checkStrength', function () {
return {
replace: false,
restrict: 'EACM',
link: function (scope, iElement, iAttrs) {
var strength = {
colors: ['#F00', '#F90', '#FF0', '#9F0', '#0F0'],
mesureStrength: function (p) {
var _force = 0;
var _regex = /[$-/:-?{-~!"^_`\[\]]/g;
var _lowerLetters = /[a-z]+/.test(p);
var _upperLetters = /[A-Z]+/.test(p);
var _numbers = /[0-9]+/.test(p);
var _symbols = _regex.test(p);
var _flags = [_lowerLetters, _upperLetters, _numbers, _symbols];
var _passedMatches = $.grep(_flags, function (el) { return el === true; }).length;
_force += 2 * p.length + ((p.length >= 10) ? 1 : 0);
_force += _passedMatches * 10;
// penality (short password)
_force = (p.length <= 6) ? Math.min(_force, 10) : _force;
// penality (poor variety of characters)
_force = (_passedMatches == 1) ? Math.min(_force, 10) : _force;
_force = (_passedMatches == 2) ? Math.min(_force, 20) : _force;
_force = (_passedMatches == 3) ? Math.min(_force, 40) : _force;
return _force;
},
getColor: function (s) {
var idx = 0;
if (s <= 10) { idx = 0; }
else if (s <= 20) { idx = 1; }
else if (s <= 30) { idx = 2; }
else if (s <= 40) { idx = 3; }
else { idx = 4; }
return { idx: idx + 1, col: this.colors[idx] };
}
};
scope.$watch(iAttrs.checkStrength, function () {
if (scope.pw === '') {
iElement.css({ "display": "none" });
} else {
var c = strength.getColor(strength.mesureStrength(scope.pw));
iElement.css({ "display": "inline" });
iElement.children('div')
.css({ "background": "#DDD" })
.slice(0, c.idx)
.css({ "background": c.col });
}
});
},
template: '<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>'
};
});
I found some code related your post, this may help you a lot
http://codepen.io/yukulele/pen/xbRpRa
var app = angular.module('app',[]);
app.controller('ctrl', function($scope){
$scope.pass="abc123456";
$scope.v=function(){
return test($scope.pass);
};
});
function test(pass){
if(pass == null)
return -1;
var s = 0;
if(pass.length<6)
return 0;
if( /[0-9]/.test( pass ) )
s++;
if( /[a-z]/.test( pass ) )
s++;
if( /[A-Z]/.test( pass ) )
s++;
if( /[^A-Z-0-9]/i.test( pass ) )
s++;
return s;
}
html{
font-size: 24px;
text-align: center;
margin: 30px;
background-color: #777;
}
label{
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<label>
password:
<input
autofocus
type="text"
ng-model="pass"/>
</label>
<label>
{{v()}}
<span ng-if="v() < 2">Weak passwrd!!</span>
<span ng-if="v() > 3">Strong password</span>
</label>
</div>

Java Script Slide Show (add slide effect)

I have a problem
this are my first steps in javascript and I'm trying to make a Javascript slide show.
I try to add a "slide in" "slide out" effect
But I don't know how I can do this.
I google about 2-3 hours but still no solution.
Please help me and give me some feedback please
Here is my code
<head>
<title>Test Slider</title>
</head>
<body>
<div id="slider" style="width: 400px; height: 200px;color: orange; font-weight: bold; font-size: 30px;font-family: sans-serif" onclick="javascript:superlink()" style="cursor:pointer;"></div>
<script type="text/javascript">
//Init//
var SlideDauer = 2000;
var ImgInX = 0;
var ImgInXposition = 0;
var background = 'url(http://www.flashforum.de/forum/customavatars/avatar47196_1.gif)';
var SldInX = 0;
var LinkInX = 0;
function superlink() {
if (!SliderKannEsLosGehen()) return false;
if (LinkInX >= SliderBilder.length) {
LinkInX = 0;
}
var Ziel = window.location.href = SliderLink[LinkInX];
++LinkInX;
}
var SliderBilder = new Array();
SliderBilder.push("http://ds.serving-sys.com/BurstingRes//Site-80313/Type-0/721dbabb-2dd5-4d92-9754-7db9c5888f48.jpg");
SliderBilder.push("http://bytes.com/images/bytes_logo_a4k80.gif");
SliderBilder.push("http://cdn.qservz.com/file/df8e9dcf202cfddedf6f2d4d77fcf07b.gif");
SliderBilder.push("http://ds.serving-sys.com/BurstingRes//Site-80313/Type-0/721dbabb-2dd5-4d92-9754-7db9c5888f48.jpg");
//SliderBilder.push("http://www.flashforum.de/forum/customavatars/avatar47196_1.gif");
var SliderTitle = new Array();
SliderTitle.push("");
SliderTitle.push("Title 1");
SliderTitle.push("Title 3");
SliderTitle.push("Title 4");
//SliderTitle.push("Title 5");
var SliderLink = new Array();
SliderLink.push("http://www.google.de");
SliderLink.push("http://spiegel.de");
SliderLink.push("http://bing.com");
SliderLink.push("http://youtube.com");
//SliderLink.push ("http://www.flashforum.de/forum/customavatars/avatar47196_1.gif");
function SliderKannEsLosGehen() {
if (SliderBilder.length < 2) return false;
return true;
if (SliderTitle.length < 2) return false;
return true;
}
//Run//
function SliderRun() {
if (!SliderKannEsLosGehen()) return false;
if (ImgInX >= SliderBilder.length) {
ImgInX = ImgInXposition;
}
if (SldInX >= SliderBilder.length) {
SldInX = 0;
}
document.getElementById("slider").style.backgroundImage = 'url(' + SliderBilder[ImgInX] + ')';
++ImgInX;
document.getElementById("slider").innerHTML = SliderTitle[SldInX];
++SldInX;
window.setTimeout("SliderRun()", SlideDauer);
}
window.setTimeout("SliderRun()", SlideDauer);
</script>
</body>
</html>
For effects i would look into JQuery and use the animate function. There is loads of fun to be had with this as long as you have an understanding of css.

Categories