i want to show the error messages next to the input element and if there's no error messages then send the data to the server (clear data from form) so fire the function on submit
http://codepen.io/anon/pen/RPNpNw
the problem is the error messages showed and disappeared quickly (blink)
but when change the input type to button
http://codepen.io/anon/pen/EjaZqe
will work but the data will be still in form and not cleared as input type="submit" will do
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<form>
<table style="width:50%;">
<tr>
<td>first name</td>
<td><input type="text" id="txtfname" /></td>
<td><span id="error"></span></td>
</tr>
<tr>
<td>age</td>
<td><input type="number" id="txtage" onblur="checkAge(txtage)" /></td>
<td><span id="errorage"></span></td>
</tr>
<tr>
<td>user name</td>
<td><input type="text" id="txtuser" /></td>
<td><span id="erroruser"></span></td>
</tr>
<tr>
<td>country</td>
<td>
<select onselect="checkSelect(this)" id="slct">
<option selected="selected" value="default">select your country</option>
<option>egypt</option>
<option>usa</option>
</select>
</td>
<td><span id="errorslct"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
</table>
</form>
<script>
function allvalidate() {
validate();
checkAge(txtage);
checkuser(txtuser);
checkSelect(this);
}
function validate() {
var txtf = document.getElementById('txtfname');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
//return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
function checkSelect() {
var select=document.getElementById('slct')
if (select.value=='default') {
document.getElementById('errorslct').innerText = ('you must choose country');
document.getElementById('errorslct').style.color = 'red';
return false;
}
else {
document.getElementById('errorslct').innerText = '';
return true;
}
}
</script>
</body>
</html>
Change
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
To:
<td><input type="submit" value="register" onclick="return allvalidate()" /></td>
Otherwise the boolean value is discarded. You also need to change allvalidate to actually return false if one of the validations fail:
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(txtage)) validated = false;
if (!checkuser(txtuser)) validated = false;
if (!checkSelect(this)) validated = false;
return validated;
}
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
well, I'm not expert but what I think is that data is not sending, you need to call the function on onsubmit event, instead of calling it on onclick event. It would send the data as well.
Related
Type apple in the input whose name is goods,and type 9 in the input whose name is price,and click submit,now confirm window pop up,whatever your click yes or no,the data will send to price.php.
My expectation:
when you click yes ,the data will send to price.php,
when you click no ,the data will not send to price.php,what's wrong for my js?
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("click",check,false);
<form action="price.php" method="post">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
The price.php is simple.
<?php
var_dump($_POST);
?>
The exit below can't prevent form data from sending to price.php.
if(flag){
return true;
}else{
exit;
}
It is no use either to change exit; into return false;.
It is no use either to change js into below.
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("submit",check,false);
The traditional way is same as The KNVB did,the key point is <form action="price.php" method="post" onsubmit="return check()"> ,to bind form's attribute onsubmit with function check.
DOM0 level event way,almost the same like the traditional way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
ob.onclick =function(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
What OP expect is the DOM2 level event way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
function check(event){
console.log(ob.type);
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("click",check);
</script>
</body>
</html>
The key points in DOM2 level event way are:
1.when flag is true
if(flag){
ob.submit();
return true;
}
2.when flag is false
else{
event.preventDefault();
return false;
}
This is my solution:
<html>
<body>
<form action="price.php" method="post" onsubmit="return check()">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
function check()
{
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
I tested it on Edge, IE11, Firefox, chrome browser, it works.
I found another solution:
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('form');
function check(event){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("submit",check);
</script>
</body>
</html>
A couple of things about the code:
exit - I've never seen before - is it javascript?
document.getElementById('price').value - returns a string - you should parse it (to a number) before comparing.
Use onsubmit="" attribute of the form - return true to allow form submission, false to block submission.
window.confirm already returns a boolean, just return that (instead of if statement).
Here's a bare-bones example:
function validate() {
const price = parseFloat(document.getElementById('price').value)
if (price < 10) {
return window.confirm("Are your sure the price is less than 10 ?")
}
return true // <- otherwise allow form submission
}
<form action="price.php" method="post" onsubmit="return validate()">
<input type="text" id="price" name="price">
<input type="submit" id="submit" value="submit">
</form>
Also, in general, try to condense your problem to the minimum code required to reproduce an issue.
How can i add prevent-default() with focus-out() in my form. I face problem when i click the reset button in my form. It show the last focusing input field error message when i click the reset button. Here my code bellow:
$(document).ready(function(){
//error message section:
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
//username validation area:
function checkUsername(){
var name = $("#username").val();
var usernameLength = $("#username").val().length;
if(!name.replace(/\s/g, '').length){
$("#username_error_msg").html("<span class='errorMessage'>Username shouldn't be empty..!</span>").slideDown(500);
}else if(usernameLength < 5 || usernameLength > 20){
$("#username_error_msg").html("<span class='errorMessage'>Username should be between 5-20 characters..!</span>").slideDown(500);
}else{
$("#username_error_msg").slideUp(500);
return true;
}
}
//Gender selection check:
function checkGenderSelection(){
var genderCategory = $('select[name=Gender]').val();
if(genderCategory == 'Select'){
$("#gender_Select_error_msg").html("<span class='errorMessage'>Please select your gender..!</span>").slideDown(500);
}else if((genderCategory == 'Male') || (genderCategory == 'Female')){
$("#gender_Select_error_msg").slideUp(500);
return true;
}
}
//job category check: radiobutton
function checkJobCategorySelection(){
var jobCategory = $('input[name=jobCategory]:checked');
if(jobCategory.length == 0){
$("#jobCategory_error_msg").html("<span class='errorMessage'>No Category Selected..!</span>").slideDown(500);
}else{
$("#jobCategory_error_msg").slideUp(500);
return true;
//By this way we can collect the value from radio button for further action//
//console.log("Selected Item: " + jobCategory.val());
}
}
//programming Experience check: checkbox
function programmingExperienceCheck(){
var experienceList = $('input:checkbox[name=language]:checked');
if(experienceList.length == 0){
$("#experience_sector_error_msg").html("<span class='errorMessage'>No Sector Selected..!</span>").slideDown(500);
}else{
$("#experience_sector_error_msg").slideUp(500);
return true;
}
}
//password validation area:
function checkPassword(){
var pass = $("#password").val();
var passwordLength = $("#password").val().length;
if(!pass.replace(/\s/g, '').length){
$("#password_error_msg").html("<span class='errorMessage'>Please type your password..!</span>").slideDown(500);
}else if(passwordLength < 8){
$("#password_error_msg").html("<span class='errorMessage'>Password should be minimum 8 characters..!<span class='errorMessage'>").slideDown(500);
}else{
$("#password_error_msg").slideUp(500);
return true;
}
}
//retype password validation area:
function checkRetypePassword(){
var pass = $("#password").val();
var retypePass = $("#retype_password").val();
if(!retypePass.replace(/\s/g, '').length){
$("#retype_password_error_msg").html("<span class='errorMessage'>Please give your password again..!</span>").slideDown(500);
}
else if(pass !== retypePass){
$("#retype_password_error_msg").html("<span class='errorMessage'>Password don't match..!</span>").slideDown(500);
}else{
$("#retype_password_error_msg").slideUp(500);
return true;
}
}
//email validation area:
function checkEmail(){
var regularExp = new RegExp(/([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})/);
if(!$("#email").val().replace(/\s/g, '').length){
$("#email_error_msg").html("<span class='errorMessage'>Please give your email id..!</span>").slideDown(500);
}
else if(regularExp.test($("#email").val())){
$("#email_error_msg").slideUp(500);
return true;
}else{
$("#email_error_msg").html("<span class='errorMessage'>Invalid Email..!</span>").slideDown(500);
}
}
//phone number validation area:
function checkPhoneNumber(){
var phone_number = $("#phoneNo").val();
var regularExp = new RegExp(/^(?:\+?88)?01[15-9]\d{8}$/);
if(!phone_number.replace(/\s/g, '').length){
$("#phone_no_error_msg").html("<span class='errorMessage'>Please enter a phone number..!</span>").slideDown(500);
}else if(regularExp.test($("#phoneNo").val())){
$("#phone_no_error_msg").slideUp(500);
return true;
}else{
$("#phone_no_error_msg").html("<span class='errorMessage'>Invalid phone number..!</span>").slideDown(500);
}
}
//short notes validation area:
function checkShortNotes(){
var shortNotes = $("#short_note").val();
var shortNotesLength = $("#short_note").val().length;
if(!shortNotes.replace(/\s/g, '').length){
$("#short_note_error_msg").html("<span class='errorMessage'>You have to write something about you..!</span>").slideDown(500);
}else if(shortNotesLength < 10){
$("#short_note_error_msg").html("<span class='errorMessage'>Your notes is too short..!</span>").slideDown(500);
}else{
$("#short_note_error_msg").slideUp(500);
return true;
}
}
//username focus action:
$("#username").focusout(function(){
if($('input[type=reset]').data('clicked',false)){
checkUsername();
}
});
//gender focus action:
$("#gender").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkGenderSelection();
}
});
//password focus action:
$("#password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPassword();
}
});
//retypePassword focus action:
$("#retype_password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkRetypePassword();
}
});
//email focus action:
$("#email").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkEmail();
}
});
//phone number focus action:
$("#phoneNo").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPhoneNumber();
}
});
//shortNotes focus action:
$("#short_note").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkShortNotes();
}
});
//form submit action:
$("#myForm").submit(function(){
if(checkUsername() && checkGenderSelection() && checkJobCategorySelection() && programmingExperienceCheck() && checkPassword() && checkRetypePassword() && checkEmail() && checkPhoneNumber() && checkShortNotes()){
return true;
}
else{
return false;
}
});
});
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
});
.errorMessage{background-color: darkcyan;color:white; border-radius:2px;font-size: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="msg.php" method="post">
<table>
<tr>
<td>Username: </td>
<td><input type="text" id="username"></td>
<td><span id="username_error_msg"></span></td>
</tr>
<tr>
<td>Select Your Gender: </td>
<td>
<select name="Gender" id="gender">
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td><span id="gender_Select_error_msg"></span></td>
</tr>
<tr>
<td>Select Job Category: </td>
<td>
<input type="radio" name="jobCategory" value="Part Time"/> Part Time
<input type="radio" name="jobCategory" value="Full Time"/> Full Time
<input type="radio" name="jobCategory" value="Intern"/> Intern
</td>
<td><span id="jobCategory_error_msg"></span></td>
</tr>
<tr>
<td>Select Experience Sector:</td>
<td>
<input type="checkbox" name="language"/> Javascript
<input type="checkbox" name="language"/> PHP
<input type="checkbox" name="language"/> Jquery
</td>
<td><span id="experience_sector_error_msg"></span></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password"></td>
<td><span id="password_error_msg"></span></td>
</tr>
<tr>
<td>Retype Password: </td>
<td><input type="password" id="retype_password"></td>
<td><span id="retype_password_error_msg"></span></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email"></td>
<td><span id="email_error_msg"></span></td>
</tr>
<tr>
<td>Phone No: </td>
<td><input type="text" id="phoneNo"></td>
<td><span id="phone_no_error_msg"></span></td>
</tr>
<tr>
<td>Short Note About You: </td>
<td><textarea id="short_note" cols="22" rows="5"></textarea></td>
<td><span id="short_note_error_msg"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit"/>
<input type="reset" value="Refresh"/>
</td>
<td></td>
</tr>
</table>
</form>
});
How can i stop to seeing any focus-out() action when i click reset button????
When you reset the form, you are hiding all the error messages. Then focus on the first element - username.
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
$('#username').focus();
});
Blur comes before click so you are setting the .html of the error, then the click comes and you hide it but because you use .slide jQuery will then set it visible again as it's sliding in.
The simplest way would be to set the html of the error to an empty string, jQuery can then slide in an empty string:
function removeErrors(){
$("#username_error_msg").html("");
$("#gender_Select_error_msg").html("");
$("#jobCategory_error_msg").html("");
$("#experience_sector_error_msg").html("");
$("#password_error_msg").html("");
$("#retype_password_error_msg").html("");
$("#email_error_msg").html("");
$("#phone_no_error_msg").html("");
$("#short_note_error_msg").html("");
}
//refresh button action:
$('input[type=reset]').click(function(){
removeErrors();
});
I've made a couple of JavaScript function and I'm looking for the best way to implement them into my web application.
The main Three functions are:
Focus()
Focus does exactly what you think it will do, it gives focus to a textbox.
This has a check build in that checks which textfield needs the focus.
The function looks something like this:
function Focus(field) {
if (Locatie.value == "" && Bonregel == ""){
Locatie.focus();
}
else if (Locatie.value == "") {
Locatie.focus
}
else if (Bonregel.value == "") {
Bonregel.focus();
}
}
And I think that I need to call use that functions as soon as the page loads.
Send()
Send does also do what you expect it do to, it sends (submits) the data from the form. And that functions looks something like this:
function Send(keycode, locatie, bonregel) {
//Assign fields to variables
Form_Keycode = document.getElementById("form_keycode");
Form_Locatie = document.getElementById("form_locatie");
Form_Bonregel = document.getElementById("form_bonregel");
// Assign values to fields
Form_Keycode.value = keycode;
Form_Locatie.value = locatie;
Form_Bonregel.value = bonregel;
//submit data from myform
document.myform.submit();
}
Check
This is the last big function that needs to be included, Check checks if which key is pressed and then uses Send() to send the information. This looks something like this:
function Check() {
// check alle data vooor verzenden
// Keycode 13 -> ENTER
// Keycode 125 -> Green key on device
Locatie = document.getElementById("locatie").value;
Bonregel = document.getElementById("bonregel").value;
if (event.keyCode == 125) {
Send(125, locatie, bonregel);
}
else if (event.keyCode == 13) {
delay(Send(13,locatie,bonregel), "Send", 500);
}
else {
Focus();
}
}
Now on to the question:
What would be the most efficient way to implement these functions into my html, and which methods should be used? my html looks like this:
<legend>Test</legend><br />
<form name="myform" action="/" method="post">
<input type="hidden" id="form_locatie" name="locatie" />
<input type="hidden" id="form_bonregel" name="bonregel" />
<input type="hidden" id="form_keycode" name="keycode"/>
</form>
<table>
<tr>
<td>Locatie:</td>
<td><input type="text" id="locatie" onkeyup="CheckLocation()" value="{locatie}" /></td>
</tr>
<tr>
<td>Bonregel:</td>
<td><input type="text" id="bonregel" onkeyup="keyup(event)" /></td>
</tr>
<tr>
<td>Bonlijst:</td>
<td><textarea id="bonregelbox" readonly></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Velden Legen" id="reset" onclick="ClearFields()" /></td>
</tr>
</table>
I would not use a different form for a function which requires javascript. I would wrap the table with a form element, add validation on event on the input fields onchange="check(this)" and keep it simple.
<form name="myform" action="/" method="post" onsubmit='return validate();'>
<table>
<tr>
<td>Locatie:</td>
<td><input type="text" id="locatie" onchange="check(this)" value="{locatie}" /></td>
</tr>
<tr>
<td>Bonregel:</td>
<td><input type="text" id="bonregel" onchange="check(this)" /></td>
</tr>
<tr>
<td>Bonlijst:</td>
<td><textarea id="bonregelbox" readonly></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Velden Legen" id="reset" onclick="ClearFields()" /></td><!-- i do not understand this! -->
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
This avoid's unnecessary assignments of values and variable declarations
1) Focus(param1,param2)
function Focus(Locatie,Bonregel) {
if (Locatie.value == "" && Bonregel.value == ""){
Locatie.focus();
}
else if (Locatie.value == "") {
Locatie.focus
}
else if (Bonregel.value == "") {
Bonregel.focus();
}
}
2) Send(param1,param2,param3)
function Send(keycode, locatie, bonregel) {
//Assign value directly
document.getElementById("form_keycode").value = keycode;
document.getElementById("form_locatie").value=locatie;
document.getElementById("form_bonregel").value=bonregel;
//submit data from myform
document.myform.submit();
}
3) Check()
function Check() {
// check alle data vooor verzenden
// Keycode 13 -> ENTER
// Keycode 125 -> Green key on device
if (event.keyCode == 125) {
Send(125, document.getElementById("locatie").value, document.getElementById("bonregel").value);
}
else if (event.keyCode == 13) {
delay(Send(13,document.getElementById("locatie").value,document.getElementById("bonregel").value), "Send", 500);
}
else {
Focus(document.getElementById("locatie"),document.getElementById("bonregel"));
}
}
I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<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';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</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>
<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 id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<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 id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...
im a bit new using javascript in HTML. I want to validate a HTML script using javascript however what i've written doesn't seem to work. Can anyone tell me where I'm going wrong???
Here is the Javascript:
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Story");
return false
}
var x=document.forms["add"]["date1"].value
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false
}
</script>
And here is the corresponding HTML script
<form name="add" action="time-sheet/insert-time-sheet.php" method="post" onsubmit="return mandatoryFields()">
<table width="500" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td width="150">Select Date:</td>
<td width="336"><input name="date" type="text" value="YYYY-MM-DD" maxlength="100" class="datepick" id="date1" /></td>
</tr>
<tr>
<td>Contract:</td>
<td><SELECT NAME="contract_id" onChange="getSprint(this.value)"><OPTION VALUE=0>--- Select Contract ---<?php echo $options_contract?></SELECT></td>
</tr>
<tr>
<td>Sprint:</td>
<td><div id="sprintdiv"><select name="sprint" >
<option>--- Select Sprint ---</option>
</select></div></td>
</tr>
<tr>
<td>Story:</td>
<td><div id="storydiv"><select name="story">
<option>--- Select Story ---</option>
</select></div></td>
</tr>
<tr>
<td>Dev Time:</td>
<td><input name="dev_time" size="20" onkeyup="ondalikSayiKontrol(this)" /></td>
</tr>
<tr>
<td>PM Time:</td>
<td><input name="pm_time" size="20" onkeyup="ondalikSayiKontrol(this)"/></td>
</tr>
<tr>
<td colspan="2"><table width="182" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="68"><input name="Submit" type="submit" id="Submit" value="Add Time Sheet" /></td>
<td width="48"><label>
<input type="reset" name="reset" value="Reset" />
</label></td>
<td width="46"><div align="center">Back</div></td>
</tr>
<input type="hidden" name="day" value="<?php echo $day; ?>" />
<input type="hidden" name="employee_id" value="<?php echo $employee_id; ?>" />
</table></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
Thanks in advance!
You're missing the closing brace on the function. If you check the error console on your browser, it will most likely tell you mandatoryFields() is undefined. Adding the closing brace will fix that. You should also return true if none of the validation fails. One last thing is that you re-declare x before each if. Not sure if it produces an error but still should be fixed.
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value;
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Story");
return false;
}
x=document.forms["add"]["date1"].value;
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false;
}
return true; // ADD THIS
} // ADD THIS
</script>
Your madatoryFields() function is not returning true when all fields are right.
from here:
If the event handler is called by the onsubmit attribute of the form
object, the code must explicitly request the return value using the
return function, and the event handler must provide an explicit return
value for each possible code path in the event handler function.
Get the right elements and perform a loop on the options inside of sprint and story.
You can use the name of your form and the names of your select boxes to access the elements straight forward.
var x = document.add.contract_id.value;
if(){
... your stuff here
}
You can also access the first form without using its name attribute.
x = document.forms[0].contract_id.value;
For sprint loop through possible options and make your alert then.
x = document.add.sprint;
var selected = false;
for (i = 0; i < x.length; ++i){
if (x.options[i].selected == true)
selected = true;
}
if(!selected){
alert("Select a story please!");
return false;
}
x = document.add.story;
selected = false;
// same procedure
You can also access the elements via getElementByID() and getElementsByTagName(), the latter returns an array of all matched elements.
document.getElementById('storydiv').getElementsByTagName('story')[0];
document.getElementsByTagName('contract_id')[0];
And dont redeclare var x in every validation step.