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.
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)
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>