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?
Related
First, i have checked several tutorial sites to clarify syntax such as the OnClick event and the prompt property and relocated the javascript from body to head (I heard this can fix browser-related problems).
For some reason OnClick event does nothing. I have tested website in-browser and radio buttons load correctly.
<!DOCTYPE html>
<html>
<head>
<script>
function checkSkillLevel() {
if(document.getElementById('skill_Easy').checked) {
var ok = prompt("You chose Easy");
}
else if(document.getElementById('skill_Medium').checked) {
var ok = prompt("You chose Medium");
}
else if document(getElementById('skill_Hard').checked) {
var ok = prompt("You chose Hard");
}
else {
var ok = prompt("Welcome to my tic tac toe game! To get started, please pick a skill level.");
}
}
</script>
</head>
<body>
<table cellpadding="10">
<tr>
<td><h1>Tic Tac Toe</h1></td>
</tr>
<tr>
<td>
<form action="" onclick="checkSkillLevel()">
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();">Easy<br>
<input type="radio" name="skill" value="Medium" id="skill_Medium">Medium<br>
<input type="radio" name="skill" value="Hard" id="skill_Hard">Hard<br>
</td>
</tr>
Also, I would prefer pure Javascript (no JQuery please) for any ideas.
You should add onclick to all the inputs, and correct the typo in the following line :
else if document(getElementById('skill_Hard').checked) {
Should be :
else if(document.getElementById('skill_Hard').checked) {
Hope this helps.
Snippet
function checkSkillLevel() {
if(document.getElementById('skill_Easy').checked) {
var ok = prompt("You chose Easy");
}
else if(document.getElementById('skill_Medium').checked) {
var ok = prompt("You chose Medium");
}
else if(document.getElementById('skill_Hard').checked) {
var ok = prompt("You chose Hard");
}
else {
var ok = prompt("Welcome to my tic tac toe game! To get started, please pick a skill level.");
}
}
<table cellpadding="10">
<tr>
<td><h1>Tic Tac Toe</h1></td>
</tr>
<tr>
<td>
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();"/>Easy<br/>
<input type="radio" name="skill" value="Medium" id="skill_Medium" onclick="checkSkillLevel();"/>Medium<br/>
<input type="radio" name="skill" value="Hard" id="skill_Hard" onclick="checkSkillLevel();"/>Hard<br/>
</td>
</tr>
</table>
Add an onclick-attr or an onchange-attr with the function to each radio-button and it will work.
It's all about which elements are listening to the onclick event. The form does not have onclick, it has onsubmit. The buttons have onclick, though.
<td>
<form action="" onclick="checkSkillLevel()">
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();">Easy<br>
<input type="radio" name="skill" value="Medium" id="skill_Medium">Medium<br>
<input type="radio" name="skill" value="Hard" id="skill_Hard">Hard<br>
</td>
Becomes:
<td>
<form action="">
<input type="radio" name="skill" value="Easy" id="skill_Easy" onclick="checkSkillLevel();">Easy<br>
<input type="radio" name="skill" value="Medium" id="skill_Medium" onclick="checkSkillLevel();">Medium<br>
<input type="radio" name="skill" value="Hard" id="skill_Hard" onclick="checkSkillLevel();">Hard<br>
</td>
Additionally, I have one other thing. Why are you using prompt() for showing the user their selection? Use alert() instead.
I have a dropdown menu and on the basis of the item selected I want to display a small part of HTML page.
<select id='menuHandler'>
<option value='abc'> abc</option>
<option value='xyz'>xyz</option>
</select>
IF the selected value is "abc" then a popup button is displayed with the following code:
<button id='runForm' onClick=""> Run form </button>
<div id ="runFormPopup" style=" display:none;">
<table CELLPADDING="10" CELLSPACING="5" class='border'>
<tr>
<td colspan='3'>Run form Generation</td>
</tr>
<tr>
<td width="200" class='border'>
<span>Input Data</span><br>
<input type="checkbox" name="vehicle" >Process log(s)<br>
Summary data<br>
<input type="checkbox" name="vehicle" >Thickness data<br>
<input type="checkbox" name="vehicle" >Particle data
</td>
<td class='border'>
<span>Steps(s)</span>
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
</td>
</tr>
<tr>
<td> Run form filename </td>
<td><input type="text" ></td>
<td><button class="editbtn">Generate</button></td>
</tr>
</table>
</div>
else if the value selected is "xyz" this should be displayed.
<form action="${ctx}/home/step50/generateReport" method="GET" id="form_generate">
<input style="margin-top: 20px;" type="submit" id="btnGenerate" class="small button active" value="Generate"/>
</form>
how can I do it.
Listen to the change event of the #menuHandler select element, and add the conditional logic there.
Example Here
$('#menuHandler').on('change', function () {
if (this.value === "abc") {
$('#runFormPopup, #runForm').show();
$('#form_generate').hide();
} else {
$('#runFormPopup, #runForm').hide();
$('#form_generate').show();
}
});
..or a shorter version:
Example Here
$('#menuHandler').on('change', function () {
var condition = this.value === "abc";
$('#runFormPopup, #runForm').toggle(condition);
$('#form_generate').toggle(!condition);
});
Try something like this.
$('#menuHandler').change(function(){
var selectedValue = $(this).val();
if(selectedValue === 'abc') {
$('#runFormPopup').show();
$('#form_generate').hide();
}
else {
$('#runFormPopup').hide();
$('#form_generate').show();
}
});
From a high-level perspective:
Create a listener on the button and listen for a click
Dynamically get the value
Either create the content for which you are looking, or insert content into a dynamically-created <div> (overlay, pop-up, etc.)
Following these steps, you should be OK.
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.
So I am doing a HTML and JavaScript related assignment which I am not required to have any prior knowledge of these scripting and programming languages. I was required to produce a document explaining how HTML and JavaScript brings about an entry form, and how JavaScript does validation check etc.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" /> : AS<br />
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
There's a task where I need to create 3 additional radio buttons for different level entries and then I was required to create a function which does a confirmation check, to ask the user to either confirm or cancel the choice after they have selected on a specific level entry. As I do not have any prior knowledge of programming(or I have learnt a little during the course of my assignment), I do not know how to create a function. Therefore, I googled it and found this page (It's the same assignment btw) From what I know from this page, I am required to change the radio buttons into:
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
and implement a function as such:
function confirmation() {
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an option');
return false;
} else {
return confirm('You have chosen '+checked.value+' is this correct?');
}
And great now I have done what it said, there's now an alert box which pops out and confirms choice of radio button with the user, so clicking on the radio button will trigger an onclick event which returns the function. Now my question is how does this function do the confirmation check?
(I am sorry if I wrote too much, my previous post was put on hold by as too broad by a few of people, because I wasn't being clear enough what I am suppose to say.)
Just add result &= confirmation(); in your validation code. Some where between your two if statements.
You need to watch the click event and determine whether or not you want to permit the action:
$(document).ready(function () {
$('input[type="radio"]').on('click', function () {
var r = confirm("Are you sure?");
if (r == true) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
});
http://jsfiddle.net/LTQ9p/1/
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">