Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to JavaScript... The following code displays correct even when I submit an incorrect value, I can't get the "else" section to work:
<!doctype html>
<html>
<head>
<script type="text/javascript">
/*<![CDATA [*/
function myFunction() {
var answer = document.getElementById('answer');
if (answer = 10)
document.getElementById("valid").innerHTML = "Correct!";
else
document.getElementById("valid").innerHTML = "Please, Try Again!";
}
/* ]]> */
</script>
</head>
<body>
<h2>What is 3+7=?</h2>
<form>
<input type="text" id="answer">
<input type="submit" onClick="myFunction(); return false;">
</form>
<div id="valid"></div>
</body>
</html>
Change your function to
function myFunction() {
var answer = parseInt(document.getElementById('answer').value,10);
if (answer === 10)
document.getElementById("valid").innerHTML = "Correct!";
else
document.getElementById("valid").innerHTML = "Please, Try Again!";
}
And it will work like a charm.
Explanation.
The element with id="answer" is an input. To retrieve value of an input, you need .value
Like var answer = document.getElementById('answer').value;
Now, this will return the value in your input type="text" as a string.
Ideally, you should parse it into the int using parseInt().
Like var answer = parseInt(document.getElementById('answer').value);
This will avoid type coersion.
Lastly, you want to compare the two values, so you need to use == operator.
Single =, an assignment operator would just assign the value and would always result into true since assignment gets successful.
And it's best practice to use strict comparison with datatypes. using === operator.
You need to use the equality operator == instead of the assignment operator =.
Also you need to get the value of the answer, not the just the element.
<!doctype html>
<html>
<head>
<script type="text/javascript">
/*<![CDATA [*/
function myFunction() {
var answer = document.getElementById('answer').value;
if (answer == 10)
document.getElementById("valid").innerHTML = "Correct!";
else
document.getElementById("valid").innerHTML = "Please, Try Again!";
}
/* ]]> */
</script>
</head>
<body>
<h2>What is 3+7=?</h2>
<form>
<input type="text" id="answer">
<input type="submit" onClick="myFunction(); return false;">
</form>
<div id="valid"></div>
</body>
</html>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
****This code is now working.
Thankyou for your input everyone.
The initial problem was that the code would run on page load, and then the second problem was that it refreshed the page on submit
After some input from a few individuals we were able to debug it together and I learned some new things.****
function check(){
let correctAns1 = 'carname = "volvo"';
let input = document.getElementById("q1").value;
let score=0;
if(input.toLowerCase() == correctAns1) {
score++;
alert("That is correct")
alert("You have a total of " + score + " points")
}else{
alert("Incorrect")
};
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
});
<div id="testForm">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1" value><br>
<input type="submit" value="Submit">
</form>
</div>
You can keep questions, scores in localstorage in JavaScript.
This information is stored in the browser and works like cookies.
ex: value inserting in localstorage:
localStorage.setItem('myCat', 'Tom');
ex: accessing to value from localstorage:
localStorage.getItem('myCat');
You Can Look:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I think you are troubled by that empty screen after submission, if yes, then the reason for that is "On form submit the page gets refreshed/redirected" to stop that use onsubmit = "check(); return false" or handle it with js using event.preventDefault.
Using return false:
onsubmit = "check(); return false"
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
};
check();
<div id="question1">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
Using preventDefault and javascript onsubmit:
e.preventDefault();
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
return false
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
check();
});
<div id="question1">
<form id="testForm" ><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
For storing, you can use localstorage on client-side. You can have an array/object of questions and answers and convert it into a string using JSON.stringify and store it in localstorage
localStorage.setItem('questionBook', JSON.stringify(questionBookObject));
and retrieve it using getItem and then JSON.parse it to get the object back.
const questionBookObject = localStorage.getItem('questionBook');
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Here's my html so far:
<html>
<body>
<head>
<script>
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
var sentances = ['This new amazing product will be in every home by 2021','Buy this now- before we run out of stock!','Get this now, before everyone else will have one!'].sample()
var quotes = ['“This is amazing!"','"Buy it Now!"'].sample()
var titleback = ['"Nothing can beat','"How can you not love'].sample()
var title = document.getElementById("title")
function myfunction() {
document.getElementById("Sentances").innerHTML = sentances;
document.getElementById("Quotes").innerHTML = quotes;
document.getElementById("Titleback").innerHTML = titleback + title;
}
</script>
</head>
<h2>Auto Ad Generator</h2>
<p>Enter the title of your product:</p>
<form method="post" action=".">
<p><input name="name" id="title"></p>
<button type="button" id="button" onclick="myfunction()">Try it</button>
<p><input name="name2" type="reset"></p>
</form>
<p id="Sentances"></p>
<p id="Sentances2"></p>
<p id="Quotes"></p>
<p id="Titleback"></p>
</body>
</html>
Though when I run this on the website (sites.google.com/view/generator-ad/home), it just prints the word 'null' next to the sentence randomly chosen from 'titleback'. Why does it do this, and not print the name of the product the user inputted at the start? I'm new to javascript and so sorry if the answer is obvious. Any help would be appreciated.
title is a reference to an element. You can't output this to the page.
Instead you presumably want its .value property, to retrieve the value entered by the user.
document.getElementById("Titleback").innerHTML = titleback + title.value;
HtmlInputElement means in this case that you are trying to print out the whole element, instead of the value.
I guess the following example can you help to solve your issue:
Array.prototype.sample = function() { return this[Math.floor(Math.random()*this.length)] };
const submitButton = document.getElementById('submit');
const titleInput = document.getElementById('title');
submitButton.addEventListener('click', e => {
const titleFromArray = ['"Nothing can beat','"How can you not love'].sample();
document.getElementById("Titleback").innerHTML = `${titleFromArray} ${titleInput.value}"`;
});
<input id="title" name="name">
<p id="Titleback"></p>
<button id="submit">Submit</button>
+1 suggestion:
Usually I like better naming convention. For example in this case when you use getElementById then I would suggest to use the variable name with the element type as well. Maybe this is just my personal preference. By doing this you will be sure that you are not mixing up values with DOM elements' references. For example in button case a better name can be just like submitButton. Other example:
const titleInput = document.getElementById('titleInput');
const title = titleInput.value;
I hope this helps!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to create a html page which will take the input from the user on the product type and print the discount on the basis of the function described in the html file. Here is the snippet of the code below. I am new to the html and java script coding. But the code is not printing the discount at all. Please suggest the way of doing it.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<h2>Product Information</h2>
<br>
<br>
<label for='Product'>Select the product to know discount</label>
<select id = 'Product'>
<option value="">--Choose a product--</option>
<option value= "gold">Gold</option>
<option value= "diamond">Diamond</option>
<option value= "silver">Silver</option>
<option value= "bronze">Bronze</option>
</select>
<br>
<p></p>
<script>
constant select = document.querySelector('select');
constant para = document.querySelector('p');
select.onchange=setDiscount;
function setDiscount() {
constant choice = select.value;
if (choice === 'Gold') {
para.textContent = 'Discount is 25';
}
else if (choice === 'Diamond') {
para.textContent = 'Discount is 15';
}
else if (choice === 'Silver') {
para.textContent = 'Discount is 10';
}
else if (choice === 'Bronze') {
para.textContent = 'Discount is 5';
}
else {
para.textContent = '';
}
}
setDiscount();
</script>
</body>
</html>
Two things:
Its constinstead of constant
You set the values as lower case "gold", "diamond", etc, but when you compare you use capital letters "Golds"
Besides that, you already have an id for select, you can use document.getElementById. The same thing for the paragraph, you can add an id to it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
In my project, there is a text box to enter the password and the password characters limit is up to 15. So, I want to display an alert message through javascript as soon as the user tries to enter the 16th character. Please help!
Try this.
function alrtMsg() {
var x = document.getElementById("pwd").value;
if(x.length > 16){
alert("maximum length is 16");
document.getElementById("pwd").value = '';
}
}
<html>
<body>
<input type="password" id="pwd" onkeyup="alrtMsg()">
</body>
</html>
Try this on Javascript:
document.getElementById("password").onkeyup = function() {
var text = document.getElementById("password").value
if(text.length> 15){
alert("too much text")
}
};
<input id="password" type="password" placeholder="password">
you need to mention your code what you tied. Anyway if you don't know try this code
<input type="text" onkeypress="myFunction(this)" maxlength="5">
<script>
function myFunction(e) {
var maxlen= e.maxLength;
if(e.value.length >= maxlen)
alert("Max length is limited to" +maxlen );
}
</script>
Using JQuery:
$("#inputFieldId").on("input propertychange", function(){
var val = this.value;
if(val.length > 15) {
this.value = val.substring(0,15); //comment if you don't want to remove the 16th character
alert("Maximum 15 characters allowed!");
}
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please help me in this issue
I want to fill all the fields with random data
https://jsfiddle.net/omrmstg7/
<html>
<head>
<script>
//<![CDATA[
window.onload=function(){
var button = document.getElementById("my-button");
var input = document.getElementById("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
input.value = names[Math.floor(Math.random() * names.length)];
});
}//]]>
</script>
</head>
<body>
<button id="my-button">Generate Random Names</button>
<input type="text" id="my-input" />
<input type="text" id="my-input" />
<input type="text" id="my-input" />
</body>
</html>
I'm guessing your problem is that you want to fill all the inputs and it doesn't do that.
The problem is that id is reserved for unique elements.
So, if you change your HTML for id to be class instead, you would change your JavaScript to something like this:
var button = document.getElementById("my-button");
var inputs = document.getElementsByClassName("my-input");
var names = ["Henry", "Joseph", "Mark", "Michael"];
button.addEventListener("click", function() {
Array.prototype.forEach.call(inputs, function (input) {
input.value = names[Math.floor(Math.random() * names.length)];
});
});
Change the inputs to use a class instead of an id.
id values should be unique in HTML and getElementById only returns the first matching id.