Require Specific First Characters from Form Post - javascript

I'm just putting this out there to see if anyone can catch my drift and give a hand..
I work for a public library and am in the process of making a "Self Checkin" machine.
Here's some code from it - There's a form called "checkin" with an input called "barcode" - the result of "barcode" is posted to a php file which the sends the data to the Library System and receives a message which is then passed into a table "completed-checkins".
It's all working fine but - I need to put some conditions on what data is accepted from the form.. The conditions are the first two characters need to be t00 .
I've been searching the web and trying to borrow/adapt code from others to make this work, which is where i got this from;
<script type="text/javascript">
function checkCode() {
var form = document.getElementById('checkin');
var x = form.elements.barcode.value.substring(0, 2);
// var x = this.value.substring(0, 2);
if (x == 't00') document.getElementById('#barcode').style.display = 'none';
}
</script>
I'm no real coder but am wondering if anyone who is can see how I could get this to work? (it doesn't at the moment).
Thanks much for looking,
Jordan.
And here's the html with all the scripts;
<body OnLoad="$('#barcode').focus();" style="padding:40px;">
<center>
<p>
<img src="selfchecklogo.png" />
</p>
<div class="formbarwrapper">
<div class="formbar">
<form method="post" name="checkin" id="checkin" onsubmit="return checkCode()" />
<input name="barcode" id="barcode" placeholder="scan an item..." autocomplete="off" maxlength="9" />
</form>
</div>
</div>
<div class="result">
<table id="completed-checkins">
<tbody>
<tr>
<td id="cell"></td>
</tr>
</tbody>
</table>
</div>
</center>
</body>
<script type="text/javascript">
function checkCode() {
var form = document.getElementById('checkin');
var x = form.elements.barcode.value.substring(0, 2);
// var x = this.value.substring(0, 2);
if (x == 't00') document.getElementById('#barcode').style.display = 'none';
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#checkin').submit(function() {
$.post("index.php", {
barcode: $('#barcode').val()
},
function(data) {
var content = '';
content += '<div class="result">';
content += '<tbody>';
content += '<tr>';
content += '<td>' + data + '</td>';
content += '</tr>';
content += '</tbody>';
content += '</div>';
$('#barcode').val('').focus();
$('#completed-checkins tbody').html(content);
});
return false;
});
});
</script>
</html>

Have you tried printing "x" to the console? I think your problem is that this line
var x = form.elements.barcode.value.substring(0, 2);
only selects the first two characters out of the string, and then you compare it to "t00", which is three characters long and thus will always evaluate to false.
Also, you might want to consider using the "===" operator instead of the "==" operator. In this case both would work, but using "===" is a good habit to get in to. "===" works the way you expect it to work, whereas "==" has some little gotchas in Javascript. For instance
0 == '0' //This evaluates to true
0 === '0' //This evaluates to false
Basically, "==" doesn't check for type, and "===" does.

Related

How to write the code in "function printOut(){} " in javascript?

I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}
There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>

JavaScript returning null on a function for a simple guessing game

I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.

Make a div-section appear event based

I have an input where I enter a small natural number, e.g. 4, and then after hitting enter it creates a special square table (the dimensions are equal to the number entered by the user). After the table there is also a button (which shouldn't be too important for this toy example).
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script type="text/javascript">
function createTable(num_rows,num_cols,idString)
{
var theader = '<table class="table table-bordered table-condensed">\n';
var tbody = '';
for( var i=0; i<num_rows;i++)
{
tbody += '<tr>';
for( var j=0; j<num_cols;j++)
{
tbody += '<td><input type="text" class="form-control" /></td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById(idString).innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
Enter Number: <input type="text" name="numberCities"
onChange='createTable(this.value,this.value,"costMatrixDiv")'><br>
Table:
<div id="tableDiv"></div>
<button>I am a Dummy-Button!</button>
</body>
</html>
The Plunker version:
https://plnkr.co/edit/DWYEbllT2ynihoTreEDY?p=preview
What I want: Before entering a number, the user can see the text "Table:" as well as the Button. However, I want those parts not being present before user input.
What I don't want: I don't want to create the text "Table:" as well as the Button in one wish with the matrix through function createTable(...). This would lead to the desired solution for this toy example, but not to the ideal solution for the more complex project I am working on. It would be ideal to create a div-section around "Table:" as well as the Button and to have a technique to make the div-section appear when the user enters a number.
Thank you!
Odd toy example and hard to give a good answer without knowing what's going on otherwise and why we're writing plain JS, but:
Put <div id="tableHolder" style="display: none;"> before Table: and </div> after </button>.
Then in your onchange, you could do:
createTable(...); showHolder(this.value);
In your script:
function showHolder(value) {
var s = document.getElementById('tableHolder').style;
var newD = value%1 == 0 && value > 0 ? 'block' : 'none';
if(s.display != newD) {
s.display = newD
}
}
So the createTable function is returning:
Uncaught TypeError: Cannot set property 'innerHTML' of null
The 3rd parameter of the onChange function on your input is trying to eventually set the innerHTML of whatever is passed to it. So if you change that to tableDiv, like so:
<input type="text" name="numberCities" onChange='createTable(this.value,this.value,"tableDiv")'>
Then it works for me.
DEMO

Why do I get a type error when trying to access the value of an element stored in a variable?

I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.

How to stop an automatic refresh using JS

I'm using javascript to create a file explorer in my website.
I have a function wich read each file from my website and change them into a caracters chain with a chain.split() for each file.
Then, in the array created, I search words that I take from a form. And then, with an innerHTML, I rewrite my HTML page with the answers.
It works, but, when the page is rewrite, it automaticly refresh, and I lose all my search reults...
I tried to stop refresh with window.stop(), document.execCommand('stop'), and it's still refresh...
Here my form :
<form name="recherche" onsubmit="javascript:maFonction()">
<INPUT class="finder" type="text" name="maRecherche" placeholder="Enter your search"/>
<input class="press" type="submit" name="search" value="Search"/>
<p style="margin-left:5%">It may take five secondes...</p>
</form>
And here, the writing part of my JS function :
var mesResultats = "";
if (bin > 0)
{
a = 0;
mesResultats += 'your search <u><b>' + words + '</u></b> can be found here : <BR><BR>';
for (var i = 0; i < mesLiens.length; i++)
{
if (mesLiens[i] != mesLiens[i-1] )
{
var monLien = '<div style="margin-left:5%; margin-right:5%; text-align:justify;">' + mesTitres[a] + '' + '<BR></div>';
mesResultats += monLien + '<hr>';
}
a++;
}
}
else
{
var monLien = 'Homepage';
mesResultats += 'No answer corresponding to your search <u><b>' + words + '</u></b>... ' + monLien + '</div>';
}
elemnt = document.getElementById("result");
elemnt.innerHTML = mesResultats;
If anyone have an idea of how to keep my search results, thank you !
(PS : I can't show you with a link...)
Add return false into the onsubmit event, to don't refresh the page.
HTML :
<form name="recherche" onsubmit="return myFunction();">
Javascript :
function myFunction(){
return false;
}
In case someone has the same situation as me, the application was using <meta http-equiv="refresh" content="3"> and was refreshing the content every 3 seconds. The solution for me was to execute window.stop(); directly from the console.

Categories