Ok so my code is below. Once the calculate price button is clicked, I want it to display the results beneath the button. ie. number of cars = CarNumber, type of car = CarType and the price of the car = CarPrice. I know this is probably super easy to do but I just cant get it to work.
HTML:
<!DOCTYPE html>
<html>
<body>
<form name="Cars">
<h1>Car Sales</h1>
<p>Which type of car would you like (A, B or C)</p>
<input type="text" name="CarType"><br>
<p>how many cars would you like (1-100)</p>
<input type="text" name="CarNumber"><br>
<br>
<button onclick="return beginfunction()">Calculate Price</button>
<p id="message"></p>
<script src="car.js"> </script>
</form>
</body>
</font>
JavaScript:
function beginfunction() {
var CarType = document.forms["Cars"]["CarType"].value;
var CarNumber = document.forms["Cars"]["CarNumber"].value;
var CarPrice;
if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
CarTypeError = "Invalid Car Type";
document.getElementById("message").innerHTML = CarTypeError;
return false;
}
{
if (isNaN(CarNumber)) {
CarNumberError = "Invalid Quantity Entered";
document.getElementById('message').innerHTML = CarNumberError;
return false;
}
}
{
if (CarNumber >0 && CarNumber <10)
{
}
else
CarError = "Invalid";
document.getElementById('message').innerHTML = CarError;
return false;
}
{
if (CarType == 'A') {
CarPrice = 30;
} else if (CarType == 'B') {
CarPrice = 20;
} else if (CarType == 'C'){
CarPrice = 10;
}
}
}
The way that you use innerHTML is right, but there is some logic problems in your function, here is the refactored code:
function beginfunction() {
var CarType = document.forms["Cars"]["CarType"].value;
var CarNumber = document.forms["Cars"]["CarNumber"].value;
var CarPrice;
var message = "";
if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
message = "Invalid Car Type";
}else{
if (CarType == 'A') {
CarPrice = 30;
} else if (CarType == 'B') {
CarPrice = 20;
} else if (CarType == 'C'){
CarPrice = 10;
}
message = CarPrice;
}
if (isNaN(CarNumber)) {
message = "Invalid Quantity Entered";
}
if (CarNumber >0 && CarNumber <10)
{
}
else{
message = "Invalid";
}
document.getElementById('message').innerHTML = message;
return false;
}
Related
I am creating a program that needs to handle three consecutive key presses of the enter button. My first eventListener works as planned. However, when the user input is incorrect, and the program moves onto the second eventListener, the program always runs the else statement regardless of whether the user input was correct or not. I tried including a variable, again, to capture user input at the second eventListener (thinking it was still reading the first user input) but the result was no different.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Enter Missing Text</title>
</head>
<body>
<p id="quote"></p>
<p id="correctResponse"></p>
<p id="incorrectResponse"></p>
<script>
let quote = ['For score and', '7', 'years ago.'];
let helper = ' ';
for (i = 0; i < quote.length; i++) {
if (i === 1) {
quote[1] = "<input type='text' id='txtBox'><br>";
}
helper += quote[i];
}
document.getElementById('quote').innerHTML = helper;
document.getElementById('txtBox').focus();
document.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var userInput = document.createElement('foo');
userInput.textContent = txtBox.value;
if (userInput.textContent == '7' || userInput.textContent == 'seven') {
document.getElementById('correctResponse').innerHTML = 'awesome.';
} else {
document.getElementById('incorrectResponse').innerHTML = "sorry. try again";
document.getElementById('txtBox').value = " ";
document.getElementById('txtBox').focus();
}
document.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
var userInput = document.createElement('foo');
userInput.textContent = txtBox.value;
if (userInput.textContent == '7' || userInput.textContent == 'seven') {
document.getElementById('correctResponse').innerHTML = 'awesome.';
} else {
document.getElementById('incorrectResponse').innerHTML = "give it one more try";
document.getElementById('txtBox').value = " ";
document.getElementById('txtBox').focus();
}
}
});
}
});
</script>
</body>
</html>
You can remove previous listener and add the next one in case the answer is wrong:
(any input value other than 7 will circle through handlers)
const result = document.getElementById('result');
function isEnter(event) {
return event.keyCode === 13
}
function f1(event) {
if (isEnter(event)) {
if (event.target.value !== '7') {
result.innerText = 'wrong 1';
event.target.addEventListener('keyup', f2);
event.target.removeEventListener('keyup', f1);
} else {
result.innerText = 'right 1';
}
}
}
function f2(event) {
if (isEnter(event)) {
if (event.target.value !== '7') {
result.innerText = 'wrong 2';
event.target.addEventListener('keyup', f3);
event.target.removeEventListener('keyup', f2);
} else {
result.innerText = 'right 2';
}
}
}
function f3(event) {
if (isEnter(event)) {
if (event.target.value !== '7') {
result.innerText = 'wrong 3';
event.target.addEventListener('keyup', f1);
event.target.removeEventListener('keyup', f3);
} else {
result.innerText = 'right 3';
}
}
}
document.getElementById('arrr').addEventListener('keyup', f1);
<input type="text" id='arrr'>
<p id='result'></p>
I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}
I want to change an image depending on what two input values have been entered. How would this be done dynamically with two separate inputs? Here's my code so far.
function twoinputs() {
var size1 = document.getElementById("size1").value;
var size2 = document.getElementById("size2").value;
var getValue = size1.value;
var getValue2 = size2.value;
if (getValue == "1" && getValue2 == "1") {
document.getElementById('optimus').style.backgroundImage = "url('http://www.orderofinterbeing.org/wp-content/uploads/2014/04/light-forest.jpg')";
} else if (getValue == "2" && getValue2 == "2") {
document.getElementById('optimus').style.backgroundImage = "url('http://freebigpictures.com/wp-content/uploads/2009/09/coniferous-forest.jpg')";
}
}
twoselects();
p {
width: 100%;
height: 200px;
}
<img class="prime" src="images/image_small.jpg">
<form>
Select image size:
<input id='size1' name='size1' onchange="twoinputs()">
<input id='size2' name='size2' onchange="twoinputs()">
</form>
<p id="optimus"></p>
First of all, inputs are self closing, so change the HTML to
<img class="prime" src="https://pbs.twimg.com/profile_images/604644048/sign051.gif">
<form>
Select image size:
<input id='size1' name='size1'>
<input id='size2' name='size2'>
</form>
<p id="optimus"></p>
In the script, the problem is that you're getting the value twice, and you've mixed up the names of the function and some variables.
You could also use proper event handlers
var elem1 = document.getElementById("size1");
var elem2 = document.getElementById("size2");
var image = document.getElementById('optimus');
function twoinputs() {
var size1 = +elem1.value;
var size2 = +elem2.value;
if (size1 === 1 && size2 === 1) {
image.style.backgroundImage = "url('http://www.orderofinterbeing.org/wp-content/uploads/2014/04/light-forest.jpg')";
} else if (size1 == 2 && size2 == 2) {
image.style.backgroundImage = "url('http://freebigpictures.com/wp-content/uploads/2009/09/coniferous-forest.jpg')";
}
}
twoinputs();
elem1.addEventListener('change', twoinputs, false);
elem2.addEventListener('change', twoinputs, false);
FIDDLE
Looks ok, but you have .value twice so size1.value will not have the attribute value, in other words:
function twoinputs() {
var size1 = document.getElementById("size1");
var size2 = document.getElementById("size2");
var getValue = size1.value;
var getValue2 = size2.value;**
if (getValue == "1" && getValue2 == "1") {
document.getElementById('optimus').style.backgroundImage = "url('http://www.orderofinterbeing.org/wp-content/uploads/2014/04/light-forest.jpg')";
} else if (getValue == "2" && getValue2 == "2") {
document.getElementById('optimus').style.backgroundImage = "url('http://freebigpictures.com/wp-content/uploads/2009/09/coniferous-forest.jpg')";
}
}
twoselects();
Am a new JavaScript programmer and am trying to make a form validator using JavaScript but the error messages don't seem to be displaying if all the forms are not filled, that is if all are empty, only the name form error displays.
This is what I tried:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
if (x == "null" || x == "") {
var b = document.getElementById("nameErr");
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
var b = document.getElementById("nameErr");
b.innerHTML = "";
return true;
}
if (y == "null" || y == "") {
var c = document.getElementById("countryErr");
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
var c = document.getElementById("countryErr");
c.innerHTML = "";
return true;
}
if (z == "null" || z == "") {
var d = document.getElementById("occupationErr");
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
var d = document.getElementById("occupationErr");
d.innerHTML = "";
return true;
}
if (a == "null" || a == "") {
var e = document.getElementById("statusErr");
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
var e = document.getElementById("statusErr");
e.innerHTML = "";
return true;
}
}
This is the JavaScript code.
<form action="process.php" method="post" onsubmit="return myValidate()" name="myform">
Name:
<input type="text" id="name" name="name">
<span id="nameErr"></span><br><br>
Country:
<input type="text" id="country" name="country">
<span id="countryErr"></span><br><br>
Occupation:
<input type="text" id="occupation" name="occupation">
<span id="occupationErr"></span><br><br>
Status:
<input type="text" id="status" name="status">
<span id="statusErr"></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the HTML form.
Please help, Thanks
It seems you don't realize that calling return ends the function you are in. If the validation fails, you'll want to return false, but you do not want to return true until the end of the validation process.
Try:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
var b = document.getElementById("nameErr");
var c = document.getElementById("countryErr");
var d = document.getElementById("occupationErr");
var e = document.getElementById("statusErr");
if (!x || x.length==0) {
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
b.innerHTML = "";
}
if (!y || y.length==0) {
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
c.innerHTML = "";
}
if (!z || z.length==0) {
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
d.innerHTML = "";
}
if (!a || a.length==0) {
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
e.innerHTML = "";
}
return true;
}
This will return the first error it comes across. If you want to check them all at once, you will need to store your true/false in a variable and hold off on any return calls until then end and call return theVariableName;
you can use a flag for save state :
http://jsfiddle.net/vEvT2/1/
var flag = true;
and change to false if find empty control
I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}