function checkvalue() {
var areaDesc = document.getElementById('areaDesc').value;
var cboLeaveType = document.getElementById('cboLeaveType').value;
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
if (areaDesc == "" || fromDate == "" || toDate == "" || cboLeaveType = "")
{
alert("empty hoys");
}
else
{
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
}
thats the code, it is working but, I want to alert those area who is still empty,
for example.
ex1: areaDesc, fromDate, toDate is not empty, it must alert "txtSignOff still empty";
ex2: areaDesc, fromDate is not empty it must alert "toDate,txtSignOff still empty";
or
toDate is empty
toDate is empty
You can use for in like this:
function checkvalue() {
var fields = {
'areaDesc' : document.getElementById('areaDesc').value;
'cboLeaveType' : document.getElementById('cboLeaveType').value;
'fromDate' : document.getElementById('fromDate').value;
'toDate' : document.getElementById('toDate').value;
};
for(var fieldName in fields){
if(fields[fieldName] == ""){
alert("field" + fieldName + "is empty");
return false;
}
}
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
You may have to split your if block into individual ones, then use a String and concatenate it with the empty field's name in each if. That is,
var emptyStr = ''
if (areaDesc == '') { emptyStr += 'areaDesc,' ; }
if (fromDate == '') { emptyStr += 'fromDate,' ; }...
...
emptyStr += ' still empty'
if (emptyStr != '') { alert(emptyStr); }
You would have to have an individual if statement for each input type you're requiring, otherwise it's a very generic error message. Something like this should do it:
Also, where is txtSignOff defined? Did you mean cboLeaveType?
If you don't want multiple alerts, just combine all the alerts from the code below and convert them into a string, and then if (error), alert the error string.
function checkvalue() {
var areaDesc = document.getElementById('areaDesc').value;
var cboLeaveType = document.getElementById('cboLeaveType').value;
var fromDate = document.getElementById('fromDate').value;
var toDate = document.getElementById('toDate').value;
if (!areaDesc) alert("areaDesc still empty");
if (!fromDate) alert("fromDate still empty");
if (!toDate) alert("toDate still empty");
if (!txtSignOff) alert("txtSignOff still empty");
if (areaDesc && fromDate && toDate && txtSignOff)
{
document.getElementById('hdnAction').value = "go";
document.frmLeave.submit();
}
}
Related
Im not really sure what Im doing wrong here. I essentially check if any of the elements values are empty, and if they are it started to iterate through them.
Once it iterates it appends the id's of the elements that are empty into the div. Or at least thats what I expected it to do. Any help? Thanks!
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++);{
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " array[i].id ";
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You terminated the for loop independently and hence you are getting out of bond index. And also as pointer by 'Xufox' that is literal string.
Find the corrected script below:
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++){
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " " + array[i].id;
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You can greatly simplify your code by doing something like this instead:
function validate() {
const requiredFields = ['username', 'name', 'phone-number', 'email', 'password', 'password-confirmation'];
const missingFields = requiredFields.filter(requiredFieldStr => {
return !document.getElementById(requiredFieldStr).value;
});
const requiredFieldError = document.getElementById('required-field-error');
if (missingFields.length > 0) {
requiredFieldError.textContent =
"The following must not be blank: " + missingFields.join('');
} else requiredFieldError.textContent = '';
}
I don't know your requirement exactly.
But if you use JQuery validation that will simplify the things for you.
function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );
I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}
I am trying to provide a message below the fields of a form. The message will depend on what is entered in both fields.
How would I go about making it so it calculates in real time using both the fields and passing it through a calculation?
Here is the fiddle http://jsfiddle.net/6qSeH/
I am using this to get the document values
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
and this at the end to run the function
yearCalculator();
There are many missing pieces in your code.
Firstly you have written code entirely using javascript and trying to use jQuery syntax. So how would you expect it to work.
jQuery to set HTML --- msg.html(value);
javascriptto set HTML --- msg.html = value;
Second When you are checking for Not a Number
It is supposed to look like
val1 === NaN // It is not a string
Also this will never work as NaN is never equal to NaN
Use isNaN() method instead
Third
<div class="message"></div>
supposed to be
<div id="message"></div>
Next you need to assign events to your input. Otherwise it would only work when the page loads for the first time..
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
Otherwise it will only work the first time your script loads.
Cleaned up code
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var msg = document.getElementById('message');
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
function yearCalculator() {
var yearOne = input1.value;
var yearTwo = input2.value;
val1 = parseInt(yearOne);
val2 = parseInt(yearTwo);
if (isNaN(val1) || isNaN(val2)) {
msg.innerHTML = "Please enter a valid year !!";
return;
}
var value1 = yearOne - yearTwo + 18;
if (yearOne == yearTwo) {
msg.innerHTML = "Both years are the same";
}
if (yearOne < yearTwo) {
if (yearTwo < value1) {
msg.innerHTML = "This is a good result";
} else if (yearTwo > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
else {
msg.innerHTML ="Year 1 is greater than Year 2";
}
};
yearCalculator();
Check Fiddle
You can use onchange="yearCalculator()" in both input fileds
First change the class='message' to id='message'. Then try this code:
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var yearOne = input1.value;
var yearTwo = input2.value;
var msg = document.getElementById('message');
function yearCalculator(value1, value2) {
msg.innerHTML='';
val1 = parseInt(value1);
val2 = parseInt(value2);
if (val1 === "NAN" || val2 === "NAN") return;
var value1 = val1 - val2 + 18;
if (val1 == val2) {
msg.innerHTML="Both years are the same";
}
if (val1 < val2) {
if (val2 < value1) {
msg.innerHTML = "This is a good result";
} else if (val2 > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
};
yearCalculator(yearOne,yearTwo);
input1.onkeyup=function() {
yearCalculator(this.value,document.getElementById("input-mini2").value);
};
input2.onkeyup=function() {
yearCalculator(document.getElementById("input-mini").value,this.value);
};
I have done a test for a gender expression -
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(gender || gender1)
{
}
else
{
errorMsg = errorMsg + "please select your gender\n"
}
}
but I would like to be able to write it so that there is no need for an empty positive outcome like this -
if ((alphabetic.test(fname)== false) || (alphabetic.test(lname)== false))
{
alertmsg = alertmsg + "Name should be in alphabets:" + "\n";
}
I am sorry if I appear to be very stupid, I am a complete beginner. any help would be appreciated, thanks
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(!(gender || gender1))
{
errorMsg = errorMsg + "please select your gender\n"
}
}
If I understand correctly:
if(!gender && !gender1) {
errorMsg = errorMsg + "please select your gender\n"
}
Not really sure what you are trying to do but, try using the logical NOT "!":
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if !(gender || gender1)
{
errorMsg = errorMsg + "please select your gender\n"
}
}