Basic HTML Function Call with buttons - javascript

I'm trying to learn basic HTML and Javascript, and am not sure what is wrong with this code. It is probably a very simple error and I'm sorry if it is. When I try clicking the buttons, Chrome says in the console that "correct" and "incorrect" are not defined, but I have checked the syntax for the functions and I can't see what is wrong. Thanks for your help :)
<!DOCTYPE html>
<html>
<head>
<title>Question 1</title>
</head>
<body>
<p>Q1: What is the height of the Eiffel Tower?</p>
<br>
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!
<br>
Next Question";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!
<br>
Next Question";
}
</script>
<button onclick="incorrect()">767m</buttton>
<br>
<button onclick="incorrect()">442m</button>
<br>
<button onclick="correct()">324m</button>
<br>
<button onclick="incorrect()">278m</button>
<p id="feedback"></p>
</body>

You have confusing ""(double quotes) in the innerHTML strings. Try this:
instead of "q2.htm" use 'q2.htm'
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>

If you look at the console log in Chrome (press F12 to enter Developer Tools where you can see the log), you will see an error message “Unexpected token ILLEGAL”. The reason is that you have line breaks inside a JavaScript string, which is not permitted, so the function definitions fail in parsing. Moreover, you are using quotes inside a quoted string, which isn’t permitted either. Use single quotes (') as inner quotes or (in this case) just omit them, e.g.
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href=q2.htm>Next Question</a>";
}

This works:
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
You have to put them on the same line or use concatenation.

Related

Javascript if statement issue: No display in the webpage

I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>

Javascript : Uncaught TypeError: Cannot read property 'length' of undefined

I have written a script that validates username submitted through form. If the user name is greater than 5 characters, it should show some message to the user.
The error that I'm getting is
:Uncaught TypeError: Cannot read property 'length' of undefined
at checkusername (eventobject.html:24)
at HTMLInputElement. (eventobject.html:18)
I have used 'blur' event.
the code is :
<html>
<head>
</head>
<body>
<form>
<label for="text">Username:</label>
<input type="text" id="text" />
<p id="para"></p>
</form>
<script>
var el=document.getElementById("text");
el.addEventListener('blur',function(){checkusername(5);},false);
var msg=document.getElementById("para");
function checkusername(min)
{
if(this.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
</script>
</body>
</html>
The above code works fine when I write the same event handler without parameters.
the code for event handling without passing parameters is shown below:
<html>
<head>
</head>
<body>
<form>
<label for="text">Username:</label>
<input type="text" id="text" />
<p id="para"></p>
</form>
<script>
var el=document.getElementById("text");
el.addEventListener('blur',checkusername,false);
var msg=document.getElementById("para");
function checkusername()
{
if(this.value.length<5)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
</script>
</body>
</html>
You can use Function.prototype.bind() to set this at first parameter and parameters to be used within function body passed at second through N parameters to .bind()
el.addEventListener('blur',checkusername.bind(el, 5 /*, N */),false);
After doing some research on the way events are called,I came across two solutions to the above problem.
Have a look at the error message again:-
:Uncaught TypeError: Cannot read property **'length'** of undefined at **checkusername**
It is clear from the above message that error is occurring inside the checkusername() function. And the actual error is happening because length is applied on undefined variable, in this context,this.
The reason for why this is undefined in this event call:
1.In regular function call(as shown below), the keyword this is associated with the event on which the function is called.
el.addEventListener('blur',checkusername(),false); //call without parameters
Here,event is calling the function checkusername() directly.In short, this is holding reference to el i.e.., this-->el.
In this kind of event call, it makes sense to use length property on this because it is holding something.
2.In the function call that involves passing parameters(problem in the question),the regular function call is not supported as per JavaScript standard. JavaScript defines that the function call needs to be embedded inside a anonymous function(as shown below):
el.addEventListener('blur',function(){checkusername(5);},false); //call with parameters.
Here,event is calling the anonymous function and which in-turn calls the checkusername(). Hence,this does not refer to anything,undefined.Therefore, calling length on this inside checkusername returns error.
since, this cannot be used, the following techniques are used.
method 1:: Passing el as part of parameters list.
var el=document.getElementById("text");
el.addEventListener('blur',function(){checkusername(el,5);},false);
var msg=document.getElementById("para");
function checkusername(el,min)
{
if(el.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
method 2: Declaring el globally.
var el=document.getElementById("text");
el.addEventListener('blur',function(){checkusername(5);},false);
var msg=document.getElementById("para");
function checkusername(min)
{
if(el.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
Found these solutions in Javascript&JQuery book by Jon Duckett..
useful link
Hope this was helpful. :) My first answer in stackoverflow.
Try this -
<!DOCTYPE html>
<html>
<body>
<form>
<label for="inputText">Username:</label>
<input type="text" id="inputText" />
<p id="message"></p>
</form>
<script>
var el=document.getElementById("inputText");
el.addEventListener('blur',function(){checkusername(5);},false);
var msg=document.getElementById("message");
function checkusername (min) {
if(this.el.value !== (undefined || null) && this.el.value.length < min) {
msg.textContent="username less than 5 characters";
} else {
msg.textContent='';
}
}
</script>
</body>
</html>
You can try this.
I hope it's will work.
<html>
<body>
<form>
<label for="text">Username:</label>
<input type="text" id="text" />
<p id="para"></p>
</form>
<script>
let element=document.getElementById("text");
element.addEventListener('blur',function(){checkusername(5);},false);
let msg=document.getElementById("para");
function checkusername(min)
{
if(element.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
</script>
</body>
</html>

Unable to link a self-executing function with html?

I am very new to Java Script. I am studying with the help of video lectures, and trying to solve the examples discussed. In the chapter Anonymous Self executing function, I am unable to link self execute function.
My codes are as follows:
Html::
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8";
</head>
<body>
<p id="message">
</p>
<script src="my2.js"> </script>
<script src="my.js"> </script>
</body>
</html>
my.js:
( function()
{
function Format(num) {
return Math.floor(num);
}
ShowMessage("You are viewing a lesson in section" + Format(9.1));
}());
my2.js:
functon ShowMessage(msg)
{
document.getElementById("message").innerHTML += Format(msg);
}
function Format(msg)
{
return "<p>" + msg + "</p>";
}
Please help me.
Is this it?
(function()
{
function Format(num) {
return Math.floor(num);
}
ShowMessage("You are viewing a lesson in section" + Format(9.1));
})();
I think you messed the brackets.
Still, this happens in javascript because you are evaluating a function as an expression.
This means that your function is only giving scope to a piece of code, and since you call it after closing de scope })();, it gets evaluated as an expression.
Following that logic, you can even do:
!function()
{
function Format(num) {
return Math.floor(num);
}
ShowMessage("You are viewing a lesson in section" + Format(9.1));
}();
That the function is also run.
[EDIT] You missed the closing '>' in your meta tag too.
Looks like you've got a few typos in your code:
In your HTML code (line 5):
<meta charset="UTF-8"> <!-- ">" instead of ";" -->
In my2.js:
function ShowMessage(msg) { // you forgot an "i" in your code
The first one will be corrected automatically in most browsers (however: you should avoid this). But the second one will raise an error and you can't call ShowMessage() anymore.
You misspelled function in my2.js
function ShowMessage(msg)
{
document.getElementById("message").innerHTML += Format(msg);
}
function Format(msg)
{
return "<p>" + msg + "</p>";
}

Execute dynamic HTML/JavaScript

I'd like to create a textarea and a division so that whatever embed code you put in the textarea it gets executed on the division in real-time.
Your kind help is greatly appreciated!
JavaScript newbie
Here's an attempt:
<script type="text/javascript">
var X = " HTML or JavaScript "
window.onload=function()
{
document.getElementById("result").innerHTML = document.getElementById("input").value;
}
</script>
<textarea id="input" cols="35" rows="7"> X </textarea>
<div id="result"></div>
This will evaluate the contents of the textarea when you click anywhere outside of the textarea. (Code updated to set result from source (<textarea/>) as HTML if source begins with a less-than ('<') or the result of evaluating source as Javascript.)
<textarea id="js" onBlur="run(this)"></textarea>
<div id="result">Result goes here!</div>
<script type="text/javascript">
function run(elt){
var target_div=document.getElementById('result'),
result='';
if(target_div) {
if(elt.value.match(/^\s*</)) { // content of textarea begins with less-than
result=elt.value;
}
else { // eval content of textarea as Javascript
try {
result=eval(elt.value);
}
catch (e) {
alert('failed to eval source:'+e.description);
}
} // else match
if(result) {
target_div.innerHTML=result;
}
} // if target_div
return false;
} // end run
</script>
Of course it's usually considered a VERY BAD IDEA to allow a user to execute arbitrary code. ;-)
Check out Eval()
Here is some code to get you started.
<textarea id='js'>window.alert('Hello Cruel World');</textarea> <input type=submit onclick="run()" value="run">
<script>
function run ()
{
eval(document.getElementById('js').value);
}
</script>

javascript error with label

I have a function as follows:
function textNext(element, num) {
document.getElementById("lblContent").innerHTML = "hello";
}
However, the text of the lblContent label won't change when the function is called.
What am I doing wrong?
btw : lblContent is of type asp:Label
Since lblControl is a server side ASP.NET control, you will need to use the control ClientID property in order to use it in javascript:
function textNext(element, num) {
document.getElementById(<"%=lblContent.ClientID%>").innerHTML = "hello";
}
Check the console in your browser for errors. I tried to reproduce your problem in a standard HTML/Javascript environment.
This works for me.
<html>
<head>
<title>Test</title>
<head>
<body>
<div id="lblContent">Previous text</div>
Change text
<script type="text/javascript">
function textNext() {
document.getElementById("lblContent").innerHTML = "Next text";
}
</script>
</body>
</html>

Categories