I want to make a quiz in PHP.
The answers are chosen from radio buttons. If the user chooses the correct answer his score adds 1 if wrong answer his score is reduced by 1.
Finally I want his score to appear as an alert.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
</head>
<body>
<?php
$score=0;
?>
<p><font size="3"> <b>There is 2 multiple choice questions<br />
Every correct answer +1 <br />
Wrong answer -1<br />
Good Luck!</b></font></p></br></br></br>
<table width="300" border="1" cellspacing="2" cellpadding="2">
<tr>
<td><p><font size="3"> <b> Question 1:
</b></font></p>
Guess The Star Of The Movie <font color="red">"The Equalizer"</font><br />
<br />
<input type="radio" name="n1" value="Denzel Washington">Denzel Washington<br>
<input type="radio" name="n1" value="Mark Wahlberg">Mark Wahlberg<br>
<input type="radio" name="n1" value="Jason Statham">Jason Statham<br>
<input type="radio" name="n1" value="Sylvester Stallone">Sylvester Stallone<br>
</form ></td>
</tr>
<tr>
<td><p><font size="3"> <b> Question 2:
</b></font></p>
Guess The Star Of The Movie <font color="red">"Game Plan"</font><br />
<br />
<input type="radio" name="n2" value="Vin Diesel">Vin Diesel<br>
<input type="radio" name="n2" value="Dwayne Johnson">Dwayne Johnson<br>
<input type="radio" name="n2" value="Liam Hamworth">Liam Hamworth<br>
<input type="radio" name="n2" value="Adam Sandler">Adam Sandler<br>
</form ></td>
</tr>
</table>
<?php
$score=0;
if($n1=="Denzel Washington")
$score = $score+1;
else $score = $score-1;
if($n2=="Dwayne Johnson")
$score = $score+1;
else
$score = $score-1;
?>
<button type="button" onclick="alert('<?php echo "your score is: ".$score.""; ?> ')">Submit</button>
</body>
</html>
When I click the submit button the score is -2 although I have chosen the correct answer
Your code is running unconditionally, EVERY time the page is loaded. That means your "is this answer right" code always declares it wrong. so effectively you've got:
$score = 0;
$score = $score - 1; // $n1 is blank, therefore wrong
$score = $score - 1; // $n2 is blank, therefore wrong
You should at LEAST be detecting if the form was actually submitted, e.g.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do scoring here ..
}
But most of that's irrelevant anyways. You don't even have a <form> tag, so there's no way for those input fields to ever submit to anything.
Related
I have a form below which uses javascript to perfom a maths equation. But i want the equation hidden, so that means replacing the JS maths equation line (var result), with a new php script. I am thinking the php code should be outside of the JS tags, perhaps using the JS variables. But i dont know much about php. I am not trying to learn php, i am just trying to get a working form, so please no convoluted lessons on how php works. I want to avoid using node js and doing ajax calls etc. If not possible please say so.
<html>
<head>
<script>
function bmi () {
var height = Number(document.getElementById("height").value);
var weight = Number(document.getElementById("weight").value);
var result = weight / (height * height);
document.getElementById("result").innerHTML = "Your score is : " + result;
}
</script>
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<form>
<h4>BMI</h4>
<input id="height" type="text" placeholder="height in meters or feet" />
<br />
<br />
<input id="weight" type="text" placeholder="weight in kgs or lbs" />
<br />
<br />
<input class = "submit" type="button" value="Submit" onclick="bmi()" />
<p id="result">Result</p>
</form>
</body>
</html>
<?php
function bmi($height, $weight) {
$height = floatval($height);
$weight = floatval($weight);
return $weight / ($height * $height);
}
?>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<form action="" method="POST">
<h4>BMI</h4>
<input id="height" name="height" type="text" placeholder="height in meters or feet" value="<?php echo isset($_POST['height']) ? $_POST['height'] : ''; ?>" />
<br/>
<br/>
<input id="weight" name="weight" type="text" placeholder="weight in kgs or lbs" value="<?php echo isset($_POST['weight']) ? $_POST['weight'] : ''; ?>" />
<br/>
<br/>
<input class="submit" type="submit" value="Submit"/>
<?php if (!empty($_POST['height']) && !empty($_POST['weight'])) : ?>
<p>Your score is <?php echo bmi($_POST['height'], $_POST['weight']); ?></p>
<?php endif; ?>
</form>
</body>
</html>
Without AJAX call, its not possible i guess if u want to use php.
Another way is, you can use angular to get your problem's solution.
I have a page that looks something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Checkbox List Validation Test</title>
<script type="text/javascript" language="JavaScript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" language="JavaScript" src="jquery.validate.js"></script>
<script type="text/javascript">
jQuery("#formUpdate").validate({
rules: Object.assign({
// TODO: validation rules?
},
messages: {
// TODO: vaidation messages?
}, mandatoryAdditionalFieldRules)
};
</script>
</head>
<body class="colorschemeBackground">
<form id="formUpdate">
<table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="100%" valign="top" class="colorschemeHeader">Pick a box. Its contents will help you on your way. <label id="Notes8Length"></label></td>
</tr>
<tr>
<td width="100%" valign="top" class="colorschemeBackground">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Box 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Box 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Box 3<br>
<script type='text/javascript'>
jQuery(function ($) {
function validateMultiple(selector, n, isExactlyN) {
const totChecked = $(selector).filter(':checked').length;
return isExactlyN ? totChecked == n : totChecked >= n;
}
var valid8 = true;
jQuery.validator.addMethod('Notes8',
function (value, element) {
if (!valid8) return true; // only one error message per multilist
valid8 = validateMultiple('.Notes8', 1);
return valid8;
},
'Please check at least one check box.');
});
jQuery('form').validate();
</script>
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="100%" valign="top" class="colorschemeHeader">What does the magic 8 ball say? <label id="Notes9Length"></label></td>
</tr>
<tr>
<td width="100%" valign="top" class="colorschemeBackground">
<input class="Notes9" name="Notes9~1" id="Notes9~1" type="checkbox" value="Yes"> Yes<br>
<input class="Notes9" name="Notes9~2" id="Notes9~2" type="checkbox" value="Yes"> No<br>
<input class="Notes9" name="Notes9~3" id="Notes9~3" type="checkbox" value="Yes"> Maybe<br>
<input class="Notes9" name="Notes9~4" id="Notes9~4" type="checkbox" value="Yes"> I don't know<br>
<input class="Notes9" name="Notes9~5" id="Notes9~5" type="checkbox" value="Yes"> Can you repeat the question?<br>
<input class="Notes9" name="Notes9~6" id="Notes9~6" type="checkbox" value="Yes"> You're not the boss of me now!<br>
<input class="Notes9" name="Notes9~7" id="Notes9~7" type="checkbox" value="Yes"> And you're not so big!<br>
<input class="Notes9" name="Notes9~8" id="Notes9~8" type="checkbox" value="Yes"> Life is unfair...<br>
<script type='text/javascript'>
jQuery(function ($) {
function validateMultiple(selector, n, isExactlyN) {
const totChecked = $(selector).filter(':checked').length;
return isExactlyN ? totChecked == n : totChecked >= n;
}
var valid9 = true;
jQuery.validator.addMethod('Notes9',
function (value, element) {
if (!valid9) return true; // only one error message per multilist
valid9 = validateMultiple('.Notes9', 1);
return valid9;
},
'Please check at least one check box.');
});
jQuery('form').validate();
</script>
</td>
</tr>
</table>
</td>
</tr>
</table>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>
Now I have two checkbox lists, Notes8 and Notes9, each with its own CSS class. I want the user to be required to check at least one check box from each list. When I initially submit the form with no check boxes checked, I get the intended error messages. However if I submit again without checking any boxes, it goes through without an error! Then it does so every other time I submit - error, goes through, error, goes through, etc. Refreshing the page resets the cycle.
Yes, I know the validation code is duplicated; it's dynamically generated code and placing the functions in the right place on the page would be tricky...
How can I get the validation code to work every time I submit the form, rather than just every other time?
I can't seem to get my function right.....It's a tuition calculator. At this point the residency and semesters don't matter. It's just credits * credit cost, but it keeps returning NaN.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Greendale Community College</title>
<script type="text/javascript">
/* <![CDATA[ */
/* ]]> */
var numCredits = 0;
var creditCost = 302;
var instate = 0;
var outstate = 0;
var international = 0;
var tuitionCost = number;
function calcTuition(numCredits, creditCost) {
var tuitionCost = numCredits * creditCost;
document.write("Your tuition cost is $" + tuitionCost);
}
</script>
</head>
<body>
<p><center><font face="impact" font size="200" color="green">Greendale Community College</font></center></p>
<center><img src="greendale.jpg" alt="greendale" width="512" height="256"/></center>
<h1><center>Tuition Calculator</center></h1>
<form name="calculator" action="" method="get">
<h2>Semester</h2>
<h3>(choose a semester)</h3>
<input type="radio" name="semesterFall"/> Fall 2018 <br />
<input type="radio" name="semesterSpring"/> Spring 2018 <br />
<input type="radio" name="semesterSummer"/> Summer 2018 <br />
<h2>Residency</h2>
<h3>(choose your residency)</h3>
<input type="radio" name="instate" /> In-State <br />
<input type="radio" name="outstate" /> Out-of-State <br />
<input type="radio" name="international" /> International <br />
<h2>Credits</h2>
<h3>(enter your number of credits)</h3>
<input type="text" name="numCredits" size="2" onchange="calcTuition(numCredits, creditCost)"/> Credits <br />
<input type="button" name="tuition" onclick="window.alert(calcTuition(numCredits, creditCost))" value="Calculate your Tuition" />
</form>
</body>
</html>
I took a look at what's going on and it looks like you're trying to call numCredits when it is not a valid number. The exact type of it is $[object HTMLInputElement]. Addition between an HTMLInputElement and Integer is undefined behavior and as a result the value that you obtain is NaN.
One possible solution is using the document.getElementbyId method to return the actual element and then you can perform any operation on them.
PS: You should try and debug your own functions, you mentioned you're new to this but it would be great to set up some print statements or use an interactive debugger to see exactly where the problem is occurring. This way you can troubleshoot it and understand the problem at the same time.
<script type="text/javascript">
var c_amount = 302;
function calcu_Tuition(Credits, c_amount) {
//var Credits
var Credits = document.getElementById("Credits").value //it will get the value of Credits text box and be transfer to Credits variable.
var tuition = 0;
var tuition = Credits * c_amount;
document.write("Your tuition cost is $" + tuition);
}
</script>
<body>
<h2>Credits</h2>
<h3>(enter your number of credits)</h3>
<input type="text" id="Credits" size="2" onchange="calcu_Tuition(Credits, c_amount)"/> Credits <br>
<button id="tuition" onclick="calcu_Tuition(c_amount)">Calculate your Tuition"</button>
</form>
</body>
I have a form in which the user inputs various information. The input chosen name allows the user to enter a username of choice but a HIDDEN INPUT needs to be integrated so that a system username is created.
The system username is generated on page submit by a javascript function, and it consists of the first alphabetic characters found in the Family name, street address, Given name; the numerical day of the month; and the numerical seconds field of the time of submission. E.g.: A user registers with name Bernardo O’Higgins, address 213 Liberator St, at 12:31:16 on 25 April 2014. His system username is
OLB2516. Just so i can see if it works, at the moment the ssytem username is not hidden but just a normal text box.
I am totally lost as i do not know how to go about this and hoping somebody can help me? Here is my php file with form integrated.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<title>Registration</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "....", ".....");
mysql_select_db("tipping291", $conn)
or die ('Database not found ' . mysql_error() );
mysql_close($conn);
?>
<div id="container">
<div id="header">
<h1>Registration</h1></div>
<div id="menu">
<h2>Homepage</h2><br />
<h2>Registration</h2><br />
<h2>User Login</h2><br />
<h2>Administrator Login</h2><br />
<h2>Tipping</h2><br />
<h2>Terms & Conditions</h2><br />
</div>
<form id="rego" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" onSubmit="return validateForm()">
<label>Given Name:</label> <input type="text" name="gname"><br />
<br />
<label>Middle Name: </label><input type="text" name="mname"><br />
<br />
<label>Family Name:</label> <input type="text" name="surname"><br />
<br />
<label>Chosen Username:</label> <input type="text" name="username"><br />
<br />
<label>Address:</label> <input type="text" name="address"><br />
<br />
<label>Postcode: </label><input type="text" name="postcode"><br />
<br />
<label>State:</label> <input type="text" name="state"><br />
<br />
<label>Tel number: </label><input type="text" name="tel"><br />
<br />
<label>Password:</label> <input type="password" name="password"><br />
<br />
<label>Password confirmation:</label> <input type="password" name="passconfirm"><br />
<br />
<label>System username</label> <input type="text" name="susername" >
<input type="submit" value="submit">
</div>
</form>
</body>
</html>
CAN SOMBODY PEASE HELP ME!!!!! I HAVENT HAD ANY SUCCESSS
I think the code found here is more suitable to generate a random string (you can put 20 characters instead of 10)
You can also just use md5() in the time or user email...
And you don't need to worry to create it in javascript, if this is random generated you can do that in php.
If you really need to do in javascript... there's CaffGeek answer in this post.. who could help you
Add the below code before closing } of function validateForm() { and try
var username = '';
var date = new Date();
$.each(['surname', 'address', 'gname'], function() {
username += $.trim($('input[name="' + this + '"]').val().replace(/\d+/g, '')).substring(0, 1);
});
username += date.getDate() + '' + date.getSeconds();
$('input[name="susername"]').val(username);
jsBin
I have this form in the index.php file :
<HTML>
<HEAD>
<TITLE>Contact Page</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<table border="0" cellpadding="0" cellspacing="3">
<form method="post" action="thankyou.php">
<tr>
<td>Name:</td>
<td><input name="name" type="text"></td>
</tr>
<tr><td>Your Browser:</td>
<td>
<select name="Browser">
<option value="Internet Explorer" selected>Internet Explorer
<option value="Mozilla">Mozilla
<option value="Other">Other
</select></td>
</tr>
<tr>
<td>Software you use:</td>
<td><input name="Microsoft Word" type="checkbox" value="yes">Microsoft Word<br>
<input name="Microsoft Excel" type="checkbox" value="yes">Microsoft Excel<br>
<input name="Adobe Photoshop" type="checkbox" value="yes">Adobe Photoshop<br>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input name="Age" type="radio" value="10-15">10-15<br>
<input name="Age" type="radio" value="16-20">16-20<br>
<input name="Age" type="radio" value="21-90">21-90<br>
</td>
</tr>
<tr><td>Other Comments:</td>
<td><textarea name="Other Comments" rows=10 cols=30></textarea></td>
</tr>
<tr><td> </td><td><input type="submit" value="Send Message"></td>
</tr></form>
</table>
and this is in my thankyou.php :
<?php
//This command imports the values from contact.php. Please do not touch.
#import_request_variables("gpc");
//The email address the message will be sent to
$youremail = "youremail#yoursite.com";
//The subject of the email you will receive;
$subject = "Our Survey";
//The page your visitor will be redirected to.
$redirect = "http://www.yoursite.com";
//Time until the page redirects your visitor (seconds)
$secs = "5";
//This takes all of the information from the form and sorts it out. Please leave as is.
foreach ($_POST as $name => $value) {
$thetext = $thetext . "$name : $value\n";
}
?>
<HTML>
<HEAD>
<TITLE>Thank you</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<table cellpadding=0 cellspacing=0>
<tr><td>
<?php
//Checks to see if the name field is empty. You can delete or add fields as needed.
if ((!empty($name))) {
$name = stripslashes($name);
$message = stripslashes($message);
//This is where the email is sent using your values from above.
mail("$youremail", "$subject", "$thetext");
?>
<meta http-equiv="refresh" content="<?php = $secs; ?>;URL=<?php = $redirect; ?>">
Thank you, we have recieved your message.
<p>
You are now being redirected to our homepage.
<?php
} else {
?>
We require your name email address and a message in order to reply to your message. Please click here or your browsers back button to try again.
<?php
}
?>
</td></tr>
</table>
I want to make "Your Browser" and/or "Other Comments:" a required field, so if the visitor doesn't fill in at least one of them, he will be redirected to some page which will say, please fill the required fields. If he fills in any of them the form should submit successfully. I know there is some basic editing needed, but unfortunately I'm just learning and couldn't do it myself.
Please help.
Try this:
<HTML>
<HEAD>
<TITLE>Contact Page</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<script>
function validateForm()
{
var x=document.forms["my_form"]["name"].value;
var y=document.forms["my_form"]["comments"].value;
if (x==null || x=="")
{
alert("name must be filled out");
return false;
}
if (y==null || y=="")
{
alert("comments must be filled out");
return false;
}
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<form method="post" action="thankyou.php" name="my_form" onsubmit="return validateForm()">
<tr>
<td>Name:</td>
<td><input name="name" type="text"></td>
</tr>
<tr><td>Other Comments:</td>
<td><textarea name="comments" rows=10 cols=30></textarea></td>
</tr>
<tr><td> </td><td><input type="submit" value="Send Message"></td>
</tr></form>
</table>
This will validate on the same page, so it will be best.
EDIT:
For only one, try like this:
<HTML>
<HEAD>
<TITLE>Contact Page</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<script>
function validateForm()
{
var x=document.forms["my_form"]["name"].value;
var y=document.forms["my_form"]["comments"].value;
var count = 0;
if (!(x==null || x==""))
{
count++;
}
if (!(y==null || y==""))
{
count++;
}
if(count < 1){
alert("Please fill at least one field");
return false;
}
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<form method="post" action="thankyou.php" name="my_form" onsubmit="return validateForm()">
<tr>
<td>Name:</td>
<td><input name="name" type="text"></td>
</tr>
<tr><td>Other Comments:</td>
<td><textarea name="comments" rows=10 cols=30></textarea></td>
</tr>
<tr><td> </td><td><input type="submit" value="Send Message"></td>
</tr></form>
</table>
Demo here>>
You can use jquery for validations in html/php forms.Try to include jquery validations in your html code.
All you have to do is just include latest version of jquery and the validate.js from github
and make the drop down list required as follows.
<select name="Browser" required="true">
And that will take care of the things.
you can also explore about validate.js from this link
*Update : *
Also you can use the html5 validations for modern browsers.
<input type="text" name="username" required="required">