JavaScript doesn't display as intended on HTML Site - javascript

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.

Related

function that targets DOM to display game results not responding despite calling function and there are no console errors either

I am trying to understand why the function endResult() does not work when either winning or losing a game of hangman.
I have called the function at the bottom of the code and there are no errors in the console.
But when the game finishes (either guessing the word completely within 5 guesses or running out of guesses), there is no action taken from this function.
This is my first intermediate challenge and I still clearly have a lot to learn but any help would be extremely welcome.
Thanks
//global variables.
//counter to display how many tries you have left at guessing correct characters.
var triesLeft = 5;
//dom targets.
var guessCount = document.querySelector("#guesses, p"); //display how many tries you have left in dom target.
var resetButton = document.querySelector(".button"); // reset buton
var displayWord = document.getElementById("puzzle") //dom target to show random word
//arrays
var words = ["hello world", "happy birthday", "you got talent", "china town", "leap frog",
"true lies", "artificial inteligence", "knoledge is power", "monday blues", "autonomous vehicles"];
var wrongGuess = [];
//pick a word randomly.
var randomiseWord = words[Math.floor(Math.random() * words.length)];
//hide all characters within [a-z] and replace with *.
var randomiseWordHide = randomiseWord.replace(/[a-z]/gi, '*');
function displayGame() {
//insert each character of the random word into a span tag hidden as *.
for (var i = 0; i < randomiseWord.length; i++) {
var spanTag = document.createElement("span");
displayWord.appendChild(spanTag);
spanTag.textContent = randomiseWordHide[i];
}
};
function makeAGuess(event) {
//if correct guess, reveal characters,
for (var j = 0; j < randomiseWord.length; j++) {
if (randomiseWord[j] === event.key) {
document.querySelectorAll("span")[j].textContent = event.key;
//else reduce tries left by 1.
} else if (!randomiseWord.includes(event.key)) {
guessCount.textContent = "Guesses Left:" + " " + (triesLeft - wrongGuess.length);
}
}
//if incorrect guess, push to array to keep count. keep this condition out of the loop.
if (!randomiseWord.includes(event.key)) {
wrongGuess.push(event.key);
}
};
function endResult() {
//if word is guessed correctly before running out of guesses.
for (var k=0; k<randomiseWord; k++) {
if (triesLeft >0 && !document.querySelectorAll("span")[j].includes("*")) {
document.querySelector("#guesses, p").textContent = "Well done, you guessed the word with" + triesLeft + " tries left.";
//if all guesses are used and word not complete.
} else if (triesLeft === 0) {
document.querySelector("#guesses, p").textContent = "Nice try, the word was" + '"' + randomiseWord + '".';
}
};
//create a reload button that displays a new random word when clicked.
function reloadScreen() {
reload = location.reload();
}
//listener for keydown
document.addEventListener("keydown", makeAGuess); // can also pass function from here.
//listener for reload button.
resetButton.addEventListener("click", reloadScreen, false);
//call functions.
displayGame();
endResult();
The function endResult() isn't called when the guess was correct or if there are no tries left. You just call the function once at script load. Therefor you should call it in the function makeAGuess():
function makeAGuess(event) {
//if correct guess, reveal characters,
for (var j = 0; j < randomiseWord.length; j++) {
if (randomiseWord[j] === event.key) {
document.querySelectorAll("span")[j].textContent = event.key;
//else reduce tries left by 1.
} else if (!randomiseWord.includes(event.key)) {
guessCount.textContent = "Guesses Left:" + " " + (triesLeft - wrongGuess.length);
}
}
//if incorrect guess, push to array to keep count. keep this condition out of the loop.
if (!randomiseWord.includes(event.key)) {
wrongGuess.push(event.key);
}
endResult();
};
Furthermore there are two issues in endResult():
triesLeft never gets updated an remains 5 -> use wrongGuess.length instead
!document.querySelectorAll("span")[j].includes("*") isn't valid - you have to loop over all span tags and check the condition separately:
function endResult() {
//if word is guessed correctly before running out of guesses.
const letters = document.querySelectorAll("span");
let solved = false;
for (let m = 0; m < letters.length; m++) {
if (letters[m].textContent == "*") {
solved = false;
break;
}
else {
solved = true;
}
}
if (wrongGuess.length < 5 && solved) {
document.querySelector("#guesses, p").textContent = "Well done, you guessed the word with" + (triesLeft - wrongGuess.length) + " tries left.";
//if all guesses are used and word not complete.
} else if (wrongGuess.length >= 5) {
document.querySelector("#guesses, p").textContent = "Nice try, the word was" + '"' + randomiseWord + '".';
}
};
Working example:
//global variables.
//counter to display how many tries you have left at guessing correct characters.
var triesLeft = 5;
//dom targets.
var guessCount = document.querySelector("#guesses, p"); //display how many tries you have left in dom target.
var resetButton = document.querySelector(".button"); // reset buton
var displayWord = document.getElementById("puzzle") //dom target to show random word
//arrays
var words = ["hello world", "happy birthday", "you got talent", "china town", "leap frog",
"true lies", "artificial inteligence", "knoledge is power", "monday blues", "autonomous vehicles"
];
var wrongGuess = [];
//pick a word randomly.
var randomiseWord = words[Math.floor(Math.random() * words.length)];
//hide all characters within [a-z] and replace with *.
var randomiseWordHide = randomiseWord.replace(/[a-z]/gi, '*');
function displayGame() {
//insert each character of the random word into a span tag hidden as *.
for (var i = 0; i < randomiseWord.length; i++) {
var spanTag = document.createElement("span");
displayWord.appendChild(spanTag);
spanTag.textContent = randomiseWordHide[i];
}
};
function makeAGuess(event) {
//if correct guess, reveal characters,
for (var j = 0; j < randomiseWord.length; j++) {
if (randomiseWord[j] === event.key) {
document.querySelectorAll("span")[j].textContent = event.key;
//else reduce tries left by 1.
} else if (!randomiseWord.includes(event.key)) {
guessCount.textContent = "Guesses Left:" + " " + (triesLeft - wrongGuess.length - 1);
}
}
//if incorrect guess, push to array to keep count. keep this condition out of the loop.
if (!randomiseWord.includes(event.key)) {
wrongGuess.push(event.key);
}
endResult();
};
function endResult() {
//if word is guessed correctly before running out of guesses.
const letters = document.querySelectorAll("span");
let solved = false;
for (let m = 0; m < letters.length; m++) {
if (letters[m].textContent == "*") {
solved = false;
break;
} else {
solved = true;
}
}
if (wrongGuess.length < 5 && solved) {
document.querySelector("#guesses, p").textContent = "Well done, you guessed the word with" + (triesLeft - wrongGuess.length) + " tries left.";
//if all guesses are used and word not complete.
} else if (wrongGuess.length >= 5) {
document.querySelector("#guesses, p").textContent = "Nice try, the word was" + '"' + randomiseWord + '".';
}
};
//create a reload button that displays a new random word when clicked.
function reloadScreen() {
reload = location.reload();
}
//listener for keydown
document.addEventListener("keydown", makeAGuess);
//listener for reload button.
resetButton.addEventListener("click", reloadScreen, false);
//call functions.
displayGame();
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 62.5%;
}
body {
background: #2B292E;
color: #fafafa;
font-family: Helvetica, Arial, sans-serif;
font-size: 1.6rem;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
span {
border-bottom: 1px solid #534f59;
display: inline-block;
font-size: 2rem;
height: 2.4rem;
line-height: 2.4rem;
margin: 0 .1rem;
text-align: center;
text-transform: uppercase;
width: 2.4rem;
}
p {
font-weight: 300;
margin-bottom: .8rem;
}
.puzzle {
display: flex;
margin-bottom: 4.8rem;
}
.button {
background: #7044a0;
border: none;
border-bottom: 2px solid #603a88;
cursor: pointer;
color: white;
font-size: 1.4rem;
font-weight: 300;
padding: .8rem;
transition: background .3s ease, color .3s ease;
}
.button:hover {
background: #5F3A87;
}
<div>
<div id="puzzle" class="puzzle"></div>
<p id="guesses"></p>
<button id="reset" class="button">Reset</button>
</div>

Placing the caret in an previous editable div and pressing enter should re-evaluate that input

I have this online code execution editable div that currently works step by step by using a function called parse. You input something (for example 7+5) and press enter and you get the result on a new line below and a new input div is created but if you go back to an previous editable input div and put in a new input and press enter it does not work correctly because a new output and input divs are created by default and the new code is not being re-evaluated.
Note that if you put in a : at the end of input in an input box (editable div) then no new output div is created. Output is hidden from view. This is by design to avoid long outputs that does not need to be displayed.
I have also tried to write a new function parse2() but then the step by step evaluation stops working. It appears to be very hard to get both (step by step and go back to old editable div and re-evaluate) to work at the same time. How can this be done? I think I need some if statement in function parse() that determines if it is new input code that being executed or old input code that being re-evaluated. I have also tried to assign a number to the input divs but I have not managed to get that to work.
function parse2(e) {
if (e.keyCode == 13) {
event.preventDefault();
if (document.getElementById("output") == null) {
CreateOutputDiv();
CreateInputDiv();
// calculates and assign values to output div
var d1 = document.getElementById(JSON.stringify(input)).innerText;
console.log("in = " + d1);
var d2 = eval(d1);
console.log("out = " + d2);
output.innerHTML = d2;
document.getElementById("count").value += '\n' + '\n' + cc;
} else if { //re-evaluates inputbox = works
var d1 = document.getElementById(JSON.stringify(input)).innerText;
console.log("new in = " + d1);
var d2 = eval(d1);
console.log("new out = " + d2);
output.innerHTML = d2;
input.focus();
} else { //re-evaluates inputbox = works
CreateOutputDiv();
var d1 = document.getElementById(JSON.stringify(input)).innerText;
console.log("new in = " + d1);
var d2 = eval(d1);
console.log("new out = " + d2);
output.innerHTML = d2;
input.focus(); }}}
JavaS.js and HTML below
// counts the number of input divs created
function increment() {
increment.n = increment.n || 0;
return ++increment.n;
}
// creates an input div
function CreateInputDiv() {
increment();
cc = increment.n;
console.log("increment.n = " + cc);
input = document.createElement("div");
input.setAttribute("id", "input");
input.setAttribute("class", "input");
input.innerHTML = "&nbsp";
input.setAttribute("contenteditable", "true");
input.setAttribute("onkeypress", "parse(event, this)");
document.getElementById('calc').appendChild(input);
input.focus();
}
// creates an output div
function CreateOutputDiv() {
output = document.createElement("div");
output.setAttribute("id", "output");
output.setAttribute("class", "output");
output.setAttribute("tabindex", "0");
output.setAttribute("contenteditable", "true");
document.getElementById('calc').appendChild(output);
}
function parse(e) {
var key = window.event.keyCode;
if (key == 13) { //keycode for enter
event.preventDefault();
var inz = input.innerText;
// check if input contains a colon. Hides output if colon exist.
if (inz.indexOf(':') > -1) {
// colon
var inz = input.innerText.replace(/:/g, '');
console.log("input without colon = " + inz);
var outz = eval(inz);
console.log("out = " + outz);
document.getElementById("count").value += '\n' + eval(cc + 1);
CreateInputDiv();
}
else {
// no colon = display output
// counter
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
// create output div
CreateOutputDiv();
// calculate and assign output value to output div
console.log("input = " + inz);
var outz = eval(inz);
console.log("out = " + outz);
output.innerHTML = outz;
// creates a new input div
CreateInputDiv();
}
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="JavaS.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta charset="utf-8" />
<style>
div:focus {
background-color: lightpink;
}
.input {
background-color: lightgreen;
width: 980px;
border: none;
font-size: 16px;
resize: none;
overflow: auto;
overflow-wrap: break-word;
}
.output {
background-color: lightblue;
width: 980px;
border: none;
font-size: 16px;
resize: none;
overflow-wrap: break-word;
}
#count {
background-color: lightblue;
color: black;
width: 25px;
height: 650px;
font-size: 17px;
resize: none;
overflow: auto;
border: none;
}
#calc{
background-color:lightblue;
overflow: scroll;
vertical-align: top;
border: none;
}
</style>
</head>
<body bgcolor="grey">
<table align="center" width="1000px" height="650px" bgcolor="lightblue">
<tr>
<td><textarea id="count" disabled>1 </textarea> </td>
<td id = "calc"></td>
</tr>
</table>
<script> CreateInputDiv(); </script>
</body>
</html>
When you are creating new input and output divs, you are applying the same id to all inputs and outputs. Instead of which you can use your counter number 'cc' to give all unique ids. Then when you call your parse function, you already are supplying parameter 'this' to it. Use 'this' to get element by id. And if the div with this output id is already present, just alter its content, otherwise create a new one.
<script>
// counts the number of input divs created
function increment() {
increment.n = increment.n || 0;
return ++increment.n;
}
// creates an input div
function CreateInputDiv() {
increment();
cc = increment.n;
//console.log("increment.n = " + cc);
input = document.createElement("div");
input.setAttribute("id", "input"+cc);
input.setAttribute("class", "input");
input.innerHTML = "&nbsp";
input.setAttribute("contenteditable", "true");
input.setAttribute("onkeypress", "parse(event, this)");
document.getElementById('calc').appendChild(input);
input.focus();
}
// creates an output div
function CreateOutputDiv() {
output = document.createElement("div");
output.setAttribute("id", "output"+cc);
output.setAttribute("class", "output");
output.setAttribute("tabindex", "0");
output.setAttribute("contenteditable", "true");
document.getElementById('calc').appendChild(output);
}
function parse(e,e2) {
//console.log(e2);
var key = window.event.keyCode;
if (key == 13) { //keycode for enter
event.preventDefault();
//console.log(e2.id);
var inId = e2.id;
var outId = "output"+ inId.substring(5);
//console.log(outId);
var inz = input.innerText;
// check if input contains a colon. Hides output if colon exist.
if (inz.indexOf(':') > -1) {
// colon
var inz = input.innerText.replace(/:/g, '');
//console.log("input without colon = " + inz);
var outz = eval(inz);
//console.log("out = " + outz);
document.getElementById("count").value += '\n' + eval(cc + 1);
CreateInputDiv();
}
else {
// no colon = display output
// counter
if(document.getElementById(outId)) {
console.log("Already created");
inz = document.getElementById(inId).innerText;
console.log(inz);
var outz = eval(inz);
document.getElementById(outId).innerHTML = outz;
}
else {
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
// create output div
CreateOutputDiv();
// calculate and assign output value to output div
//console.log("input = " + inz);
var outz = eval(inz);
//console.log("out = " + outz);
output.innerHTML = outz;
// creates a new input div
CreateInputDiv();
}
}
}
}
</script>

Displaying Password Meter Strength Level

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";
}
}

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)

using jQuery to append div's and each div has a different ID

So I'm trying to to use jQuery to append a div which will generate a card using the assigned class. The problem is I need to create a different ID each time so I can put random number on the card. I'm sure there's an easier way to do this. So i'm posing two questions. how to make the code where it put the random number on the card go endlessly. and how to append divs with unique ID's. Sorry if my code isn't the best. It's my first project.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<title></title>
<style>
.cardLook {
border: 1px solid black;
width: 120px;
height: 220px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,#card2,#card3,#card4,#card5 {
transform:rotate(180deg);
}
#cardTable {
background-color: green;
height: 270px
}
.reset {
clear: both;
}
</style>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<button id="deal">Deal</button>
<button id="hit">hit</button>
<button id="stand">Stand</button>
<button id="hi">hi</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<div id="cardTable">
</div>
<div class="reset"></div>
<script>
var what;
//Services helper functon
document.getElementById('deal').onclick = function deal() {
var score1 = Math.floor(Math.random() *10 + 1);
var score2 = Math.floor(Math.random() *10 + 1);
var firstCard = score1;
var secondCard = score2;
//myNumberArray.push(firstCard, score2);
//card1.innerHTML = myNumberArray[0];
//card2.innerHTML = myNumberArray[1];
$("#deal").click(function(){
$("#cardTable").append("<div class='cardLook' id='card1'></div>");
});
console.log(score2, score1)
}
var myNumberArray = [];
$("#hit").click(function(){
$("#cardTable").append("<div class='cardLook' id="uniqueIdNumberOne"></div>");
if (myNumberArray > 1) {
#cardTable
}
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
card1.innerHTML = myNumberArray[0];
card2.innerHTML = myNumberArray[1];
card3.innerHTML = myNumberArray[2];
card4.innerHTML = myNumberArray[3];
card5.innerHTML = myNumberArray[4];
// console.log("myNumberArray: ", myNumberArray);
what = calcTotal(myNumberArray);
showMe(calcTotal(myNumberArray));
});
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
console.log("myNumberArray: ", myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
if (calcTotal(myNumberArray) > 21) {
alert('you lose');
}
};
document.getElementById('stand').onclick = function stand() {
var compterDeal1 = Math.floor(Math.random() *10 + 1);
var computerCards = compterDeal1;
console.log(computerCards);
computerArray.push(computerCards);
if (computerCards < 21) {
stand();
}
}
var computerArray = [];
</script>
</body>
</html>
Use an unique class with all of then, and call then by class
Add a global integer:
var cardNumber = 0;
A function to generate an id:
function newCardId() {
cardNumber ++;
return 'uniqueCardId' + cardNumber.toString();
}
And use:
var newId = newCardId();
$("#cardTable").append("<div class=\"cardLook\" id=\"" + newId + "\"></div>");
Finally to access your new div:
$('#' + newId).
Note: Escape quotes within a string using backslash!

Categories