HTML onfocus not calling Javascript function - javascript

So I'm making a kind of like a telltale game using readonly inputs. I'm using onfocus to call a javascript function, but it won't run the function. I'm new to stackoverflow so if you can't see my code, please tell me. Also, I'm coding on Chromebook so the links to the CSS file and JS file are drive links.
EDIT: I think this is a problem on my computer's end since it's working perfectly fine when I run it on here.
EDIT 2: MY GOD I'M AN IDIOT! I misspelled something in the javascript section, something that DIDN'T EVEN MATTER TO MY GAME was MISSPELLED.
var meep = 0;
function changeText() {
document.getElementById("startInput").blur();
if (meep === 0) {
document.getElementById("startInput").value = "'Why are you here?'";
} else if (meep === 1) {
document.getElementById("startInput").value = "'I'm not who I used to be...'";
} else if (meep === 2) {
document.getElementById("startInput").value = "'I'm looking for Malya,' you say.";
} else if (meep === 3) {
document.getElementById("startInput").value = "'I assume that is you.'";
} else if (meep === 4) {
document.getElementById("startInput").value = "...";
}
meep++;
}
<link rel="stylesheet" href="file:///media/fuse/drivefs-ba3df23145370ebbe0addbed7174e8b0/root/html/New%20Website/style.css">
<script src="file:///media/fuse/drivefs-ba3df23145370ebbe0addbed7174e8b0/root/html/New%20Website/code.js"></script>
<body>
<input type="text" class="no-outline" value="'Who are you?'" id="startInput" onfocus="changeText()" readonly>
<input type="text" class="tutorial" id="tutorial" placeholder="Click on text to change it." readonly>

Yeah, something that didn't matter to my game, I took out of the code for stackoverflow and OF COURSE it was misspelled. So the solution, when making a random variable you don't even need, do NOT spell document as doument.

This works just fine.
If it doesn't work on your machine, please check out the console do you have any errors, because the line
<script src="file:///media/fuse/drivefs-ba3df23145370ebbe0addbed7174e8b0/root/html/New%20Website/code.js"></script>
could create problems if the script doesn't work right.

Related

JavaScript function() is not a function

I have a strange error Or I'm being dumb and when I search for my error I don't get the answer I need.
I am trying to have some javascript run if a certain key "/" is pressed in a text box.
Here is the Code:
function ClockIn(){
var kb_press = event.keyCode;
if(kb_press == 47)
{
alert("you are clocking in");
if(document.ClockIn.status.value === "IN"){
alert("You Cant Clock in wile you are already Clocked in\n Please try again!")
document.ClockIn.tx_Barcode.value, document.ClockIn.status.value, document.ClockIn.name.value = "";
}
}
}
<form method="POST" name="ClockIn">
<lable>Type your BarCode <input type="text" name="tx_Barcode" id="tx_Barcode" class="tx_Barcode" onkeypress="ClockIn()" ></lable><br>
<lable>Is your Name? <input type="text" name="name"></lable><br>
<lable>You are currently Signed <input type="text" name="status"></lable><br>
</form>
My result is: ClockIn is not a function
The problem here is you've named your "ClockIn" form, so due to age-old quirks in how HTML interacts with JavaScript, the ClockIn form overwrites your global ClockIn function.
Maybe rename the form "ClockInForm"? Better yet, though, you might want to use document.getElementById("...") to refer to elements.

window.location.href does not work, it always returns an alert

I have been learning HTML/CSS/JS in my free time. I'm still a noobie and I have encountered this problem while practicing.
I want to create a form where you can type what are you searching for and sumbit button redriects you to google and If it's empty it shows an alert. But the redirect does not work, I always get an alert.
Can you guide me what Am I doing work ?
Sorry for my english, It isn't my native langue.
<form id="myform">
<input type="search" name="searchedValue">
<input type="submit" value="Szukaj">
</form>
<script>
$("document").ready(function() {
$("#myform").submit(function(e) {
var searchedValue = $("input[name='searchedValue']").attr("value");
if (searchedValue) {
window.location.href = "http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
} else {
alert("empty string");
}
e.preventDefault();
});
});
</script>
var searchedValue = $("input[name='searchedValue']").val()
you should use val()
instead of attr(). Rest of the things are fine.
<form id="myform">
<input type="search" name="searchedValue">
<input type="submit" value="Szukaj" onclick="search(event)">
</form>
<script>
function search(event) {
// [0] gets the first textbox of current page with name.
var searchedValue = document.getElementsByName('searchedValue')[0].value;
if (searchedValue && event) {
event.preventDefault(); // cancels the event if it is cancelable
var specs = "height=auto,width=auto";
var searchUrl = "http://www.google.pl/#hl=plf&output=search&q=" + searchedValue;
window.open(searchUrl, "_blank", specs);
} else {
alert("empty string");
}
};
</script>
Useful links like window.open() and preventDefault(). I think it's better to practice with pure javascript and DOM manipulations when you are learning. Anyway, keep up the hard work. :)
Code is fine, i think your browser is blocking your redirect to
http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
It may happen when you have https website and want to redirect to http.
Console will silently display error regarding insecure redirect.

Javascript code not working unless there are no spaces. Why?

Ok so I am running into a really weird bug on my Wordpress site that hope is just my ignorance because this just seems too weird.
So I am working with styling a couple of input tags as well as a ReCaptcha form. I found some documentation at https://developers.google.com/recaptcha/old/docs/customization that I have been following. Basically what I want is the clean theme listed at that link and to do some showing/hiding of the captcha based on certain events.
I do realize that the top of the article mentions this version of the api is old, but the plugin I am using has some recaptcha code entangled in their code, so I figured I would try this first instead of making major modifications to the plugin.
So here is the code I am using
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
<!-- End code added by me -->
<script>
function validateGoodNewsUser(frm, requireName) {
requireName = requireName || false;
if(requireName && frm.goodnews_name.value=="") {
alert("Please provide name");
frm.goodnews_name.focus();
return false;
}
if(frm.email.value=="" || frm.email.value.indexOf("#")<1 || frm.email.value.indexOf(".")<1) {
alert("Please provide a valid email address");
frm.email.focus();
return false;
}
// check custom fields
var req_cnt = frm.elements["required_fields[]"].length; // there's always at least 1
if(req_cnt > 1) {
for(i = 0; i<req_cnt; i++) {
var fieldName = frm.elements["required_fields[]"][i].value;
if(fieldName !='') {
var isFilled = false;
// ignore radios
if(frm.elements[fieldName].type == 'radio') continue;
// checkbox
if(frm.elements[fieldName].type == 'checkbox' && !frm.elements[fieldName].checked) {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
// all other fields
if(frm.elements[fieldName].value=="") {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
}
}
}
return true;
}
</script>
<form method="post" class="goodnews-front-form" onsubmit="return validateGoodNewsUser(this,false);">
<div><label>Your Name:</label> <input type="text" name="goodnews_name"></div>
<div><label>*Your Email:</label> <input type="text" name="email" onfocus="toggleCaptcha(this)"></div>
<p><script type="text/javascript" src="<!--Captcha api url here-->"></script>
<noscript>
<iframe src="<!--Captcha api url here-->" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript></p>
<div><br>
<input type="submit" value="Subscribe">
</div>
<input type="hidden" name="goodnews_subscribe" value="1">
<input type="hidden" name="list_id" value="1">
<input type="hidden" name="required_fields[]" value="">
</form>
So the problem I am running into is when I load the page, I see the clean theme for ReCaptcha and the alert shows up when I click inside the input box for the email. But if I change my added code by adding a single space like this
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
<<<<<<<< Single new line space added.
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
The whole thing breaks and the page loads with the standard red ReCaptcha and my functions don't get called.
I don't mind not using spaces, but that seems very odd that a space would make the difference. Am I missing something here? Is this caused by the outdated api?
Edit:
I was asked to try to get a jsfiddle working (or not working???). I stripped out everything except the form and the function call. Even the ReCaptcha was taken out and I still can not get it to call the function. This may be my lack of knowledge on jsfiddle or it may get closer to the real problem. https://jsfiddle.net/b257779t/

Simple Guess my Number Game in Javascript

I'm working on a javascript program that is a simple guessing game. It comes up with a random number between 1 and 10 and provides an input field and a button for the user to make their guess. The program tells after each guess whether the user guessed too high or too low, and it keeps up with the number of guess it took the user to get the correct answer which it displays along with a "congratulations" message when they get it right.
I'm having some trouble getting it to work properly. The page displays properly, but when I enter a guess and click my submit button, nothing happens.
Here is my code:
<html>
<head>
<title>Guess My Number</title>
<script type="text/javascript">
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum() : function() {
this.num = parseInt(Math.random() * 10) +1;
},
checkNum() : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
alert("Correct! It took you " + this.turns + "turns to guess my number.");
return true;
}
else if(guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
}
else (guess < this.num) {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="button" value="Reset Game" onclick="resetGame()" />
</p>
</body>
</html>
I've never actually worked with Javascript before so I know this is probably a very basic thing that I'm overlooking. Any ideas as to why this isn't working correctly?
You variable guess is undefined.
Just initialize it with :
var guess = 0;
However be careful there's a possibility that num is initialize to 0. So, the user guessed immediatly without doing nothing.
var num = Math.random() *10 + 1;
BR
You should call your function in first place, one possible thing you can do is:
<input type = "button" value = "Submit Guess" onclick="guessNumber()">
now that your function is called you need to get the value entered by the user into your guess variable, which I don't see in your code, you can do it as:
Your guess:<input type = "text" name = "guess" size = "10" id="guess" /> <br />
and then in your java script initialize the variable guess as:
guess=document.getElementById("guess").value;
This should do the thing!
EDIT:
Also make sure that Math.random() returns an Integer,as others have suggested use Math.ceil() !
Several other answers have pointed out some issues in the test code:
type="submit" but no <form> tags.
Misspelled variable name tunrs instead of turns.
Use of the while loop
No event connections between the buttons and the JavaScript
This is a simple code example, and there are so, SO many ways to tackle it in JavaScript. Here is my method.
When creating a simple game board where the page does not need to be reloaded, I like to create a game object. In JavaScript you can create objects in a variety of ways. But one of the simplest is this:
var game = {};
This creates an empty object with no properties or methods. To create a couple of properties:
var game = {
num: 0,
turns: -1
};
Each of these properties can be referenced globally like var x = game.num;. To create the object with a function:
var game = {
num: 0,
turns: 0,
reset: function() {
this.turns = 0;
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
//Note: "this" lets you refer to the current object context. "game" in this case.
//There are a couple of ways to force the value to an Int, I chose parseInt
}
};
Game now has a game.reset() function that will set game.turns back to 0 and get a new game.num. Here is the full javascript code for my example (slightly different than the above examples):
<script type="text/javascript">
//Create an object to hold the game info
var game = {
num : 0,
turns : 0,
reset : function() {
//function to reset
this.turns = 0;
this.newNum();
},
newNum : function() {
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
},
checkGuess : function(guess) {
//try to convert the guess into a integer
try {
guess = parseInt(guess);
} catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
//perform strict check of equality
if (guess === this.num) {
alert("Correct! It took you " + this.turns + " turn(s) to guess my number");
return true;
} else if (guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
} else {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
Note: I didn't do a window.onload event here because those are only needed when the code will be interacting with elements on the document, or DOM elements. If you try to execute JS code in the head of the document, it gets executed instantly before the rest of the document gets loaded. This is bad if your JS code is trying to get, set, or manipulate elements in the page because you're still in the head and the body hasn't been loaded yet.
So in the case where your code needs to get access to elements of the page, often a window.onload = someInitFunction(); will be used so that the JS code will be executed after the document has completed it's load.
Below is my HTML code. It is mostly similar to your code except that I change the name attribute to id on the "guess" input to make it easier to access with document.getElementById(). Using name is helpful when you are in a form and will be submitting values to a server. Only fields with the name attribute set get submitted in that case. Often on forms you will have something like <input type="text" id="textfield" name="textfield" />. The id is used in JavaScript for easy of access, and name is used when submitting the form back to the server.
I also added onclick attributes to the buttons, and changed the input type="submit" to input type="button".
<h1>Would You Like To Play A Game?</h2>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Instructions</h2>
<p>
The game is very simple, I am thinking of a non-decimal number between 1 and 10
and it is your job to guess what that number is. If you do not guess my number
correctly on your first attempt, that's ok, you can keep guessing until you are correct.
</p>
<p>
Your guess:<input type="text" id="guess" size = "10" />
<br />
<input type="button" value = "Submit Guess" onclick="guessNumber()" />
<input type="button" value = "Reset Game" onclick="resetGame()" />
</p>
Here is a JSFiddle example that operates, I believe, the way you want it to.
update
As I was saying there are so many ways to do this. Here is an alternate way to give number selections.
A few issues with your code:
Math.random()*10 will return something that looks like 8.523525235, so you'll have a hard time matching that to any guesses. Instead, use Math.ceil(Math.random()*10). This generates a random number and then rounds up to the nearest integer.
In your JavaScript code, you're calling guessNumber() on the last line, which will execute the function as soon as the browser gets to that line. This will mean the function being executed before the user puts in any guesses. Instead you need to attach an event listener to the button, so that when the button is clicked, guessNumber() is called. Something like:
document.getElementById('button').addEventListener('click', guessNumber).
Right now you're not setting the variable guess in any way. You need to grab the value of the text box and assign that to guess. Something like:
guess = document.getElementById('textbox').value
Using a while loop is not appropriate here, since the user is using the textbox and the button to submit guesses each time. There are ways of doing this with a while loop, but let's stick with your current setup.
You want something that resembles this:
HTML:
<p>Your guess:
<input type="text" id="textbox" />
<input type="button" id="button" value="Guess" />
</p>
JS:
var rand = Math.ceil(Math.random()*10);
var turns = 0;
var guess;
document.getElementById('button').addEventListener('click', guess);
function guess() {
guess = document.getElementById('textbox').value;
if (guess == rand) {
alert('Correct! It took you ' + turns + ' turns to guess the number!');
} else if (guess < rand) {
alert('Your guess is too low. Try again.');
turns++;
} else if (guess > rand) {
alert('Your guess is too high. Try again.');
turns++;
} else {
alert('You didn\'t enter a number. Try again.');
}
}
Here's a fiddle. I added some for the reset functionality.

Changing css over if condition

HTML:
<div id="register_error">
<?php
echo "$error_msg";
?>
</div>
JavaScript:
if(document.getElementById("register_error").innerHTML)
{
document.getElementById("signUpFormBackground").style.display = "block";
}
I want the JavaScript code to check every time the page loads if there is any text in the #register_error div, though my code doesn't seem to work, why is that? What am I missing? If any more information is needed just ask.
EDIT---------------------------------
I've cleared the whitespace as some of you said
<div id="register_error"><?php echo "$error_msg";?></div>
but it didn't helped, I think the problem is that this part of code never gets called,I haven't made it in function,I just wrote it in script tags. Also tried .trim() and .length() methods, but still same response.
EDIT2--------------------------------
I've made
enter code hereif(document.getElementById("register_error").innerHTML)
{
document.getElementById("signUpFormBackground").style.display = "block";
}
else
{
document.getElementById("signUpFormBackground").style.display = "block";
}
and nothing happens,so I guess my problem is that I don't even get my code to start working,I always thought that if I put it in between script tags it'll always run at least once as web loads,so how do I actually run it on windows load,I've already tried this:
<script>
window.onload
{
if (document.getElementById("register_error").innerHTML.length > 0 )
{
document.getElementById("signUpFormBackground").style.display = "block";
}
else
{
document.getElementById("signUpFormBackground").style.display = "block";
}
}
</script>
RESULT-----------------------------
Finally found my mistake,I didn't called the function and thought It'll do stuff without calling it, the code was fine.
Any amount of whitespace can throw off your .innerHTML check, and it looks like you have some already. try this:
<div id="register_error"><?php echo "$error_msg";?></div>
Javascript:
if(document.getElementById("register_error").innerHTML == '')
{
document.getElementById("signUpFormBackground").style.display = "block";
}
You can also check to see if innerHTML.length > 0:
if(document.getElementById("register_error").innerHTML.length > 0)
While not ideal, you can also move your error logic into your php:
<?php
if ($error_msg != '')
{
echo "<style>#signUpFormBackground { display: block;}</style>";
}
?>
You have your php code indented. Thus, the innerHTML has text even if there is nothing output from the PHP code. You should trim() your innerHTML before checking if it is empty
document.getElementById("register_error").innerHTML.trim()
Example
I guess the issue is in the below if condition:
document.getElementById("register_error").innerHTML
Your inner html returns a string, so you must be checking its length as:
if(document.getElementById("register_error").innerHTML.length) {}

Categories

Resources