I've been struggling over this all day. All the other validation works fine except for the check boxes. It seems to validate it but doesn't detect when things are checked. Meaning, I'll check a box and it'll still say to enter in a contact time, no matter what box I check. Please help!!
Its just the one for selecting the best time to contact you that's acting up.
Here's my check boxes:
<input id="best_contact_time" name="best_contact_time" value="Morning 7-12" class="inputCheckbox" type="checkbox">Morning (7-12)<br>
<input id="best_contact_time" name="best_contact_time" value="Afternoon 12-5" class="inputCheckbox" type="checkbox">Afternoon (12-5)<br>
<input id="best_contact_time" name="best_contact_time" value="Evening 5-9" class="inputCheckbox" type="checkbox">Evening (5-9)<br>
And my validation code:
function submitme() {
// Validate required fields
if (get_element('lastname').value == '') {
alert('Please enter your last name');
return false;
}
if (get_element('first_name').value == '') {
alert('Please enter your first name');
return false;
}
if (get_element('phone').value == '') {
alert('Please enter a phone number');
return false;
}
if (get_element('email').value == '') {
alert('Please enter an email address');
return false;
}
var ischecked = 0;
for (var i = 0; i < document.rental.best_contact_time.length; i++) {
var e = document.rental.best_contact_time;
if (e.checked == true)
{ ischecked = 1; }
}
if (ischecked == 0) {
alert('Please enter the best time to contact you');
return false;
}
if (get_element('approximate_start_date').value == '') {
alert('Please enter an approximate start date');
return false;
}
document.forms[0].submit();
return true;
}
Since you have multiple elements with the same name, document.rental.best_contact_time will be a NodeList not an HTMLElementNode.
You would need to loop through the list (treat it like an array) and check each one in turn.
Related
I have the following JavaScript function which is triggered by an onclickevent and is working fine.
<script>
function validateForm() {
let xgame_name = document.forms['myForm']['game_name'].value;
if (xgame_name == '') {
alert('Game Name must be filled out');
return false;
}
let xdev_name = document.forms['myForm']['developer_name'].value;
if (xdev_name == '') {
alert('Developer Name must be filled out');
return false;
}
let xdev_email = document.forms['myForm']['email'].value;
if (xdev_email == '') {
alert('Developer Email must be filled out');
return false;
}
let xdemo_rom = document.forms['myForm']['demo_rom'].value;
if (xdemo_rom == '') {
alert('Demo Rom must be uploaded');
return false;
}
let xpromo_image = document.forms['myForm']['promo_image'].value;
if (xpromo_image == '') {
alert('Promo must be uploaded');
return false;
}
}
</script>
I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.
let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
let xcover_art = document.forms['myForm']['cover_art'].value;
if (xcover_art == '') {
alert('If Cartridge is selected you must proved Cover Art');
return false;
}
}
This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?
I created a contactus form on my website, and I have few js functions that check if the values are valid or not. What currently happens is - the functions do work, they check what they are supposed to, and the alert shows as well - But after all the alerts showed, it still submits the form.
I tried to use the Prevent method, and the window.back.history but none worked...
How can I fix it?
JavaScript part:
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
e.preventDefault();
window.history.back();
}
}
document.getElementById("gender").addEventListener('click',checkradio);
function checkradio() {
if(document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false ){
alert("Please select your gender");
return false;
e.preventDefault();
window.history.back();}
}
function checkbox(){
if (document.querySelector('#cbr:checked') == null){
alert("Please choose a subject");
return false;
e.preventDefault();
window.history.back();
}
function agecheck(){
var x = document.forms["contactus"]["age"].value;
var y = 18;
if(x<y)
{
alert("Please submit the form only if you're 18 yo");
return false;
e.preventDefault();
window.history.back();
}
}
}
</script>
My HTML part uses the submit method and links to:
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="validateForm1();checkbox();checkradio();agecheck()" style="float:right;text-align: right; direction: rtl;">
I think you can put 'return' in 'onsubmit'.
<script>
function validateForm1() {
var firstname = document.forms["contactus"]["fname"].value;
if (firstname == "") {
alert("Please provide your first name");
return false;
}
if (document.getElementById("genderm").checked == false && document.getElementById("genderf").checked == false && document.getElementById("gendero").checked == false) {
alert("Please select your gender");
return false;
}
if (document.querySelector('#cbr:checked') == null) {
alert("Please choose a subject");
return false;
}
var x = document.forms["contactus"]["age"].value;
var y = 18;
if (x < y) {
alert("Please submit the form only if you're 18 yo");
return false;
}
}
</script>
<form id="contactus" name="contactus" action="http://jkorpela.fi/cgi-bin/echo.cgi" onsubmit="return validateForm1();" style="float:right;text-align: right; direction: rtl;"></form>
In your form for each you can use the required tag so they always have to input something into the field.
For example
<input type="text" id="username" name="username" required>
I have five fields, four text and one textarea that need to be required. However, they all don't need a value. At least one does though. They have been grouped with the class 'onair' and what I want is to integrate them into my current validate() script in the header if possible or at least show an alert message indicating that at least one field must be entered.
Here's what I got for a form validator in the /head.
<script language="javascript">
<!--
function validate(join)
{
//
// Check for a first name.
//
if (join.fname.value.length == 0)
{
alert("Please enter your first name.");
join.fname.focus();
return false;
}
//
// Check for a last name.
//
if (join.lname.value.length == 0)
{
alert("Please enter your last name.");
join.lname.focus();
return false;
}
//
// Check for an e-mail address.
//
if (join.email.value.length < 5)
{
alert("An email address is required to proceed.");
join.email.focus();
return false;
}
//
// Check for a valid e-mail address.
//
if (join.email.value.indexOf("#",".") == -1)
{
alert("A valid e-mail address is required to proceed.");
join.email.focus();
return false;
}
// It continues.
</script>
As you can see, for the most part, this does fine. However, these only work for a single field. This is the group I'm having trouble with.
<input type="text" class="onair" id="facebook" name="facebook" />
<input type="text" class="onair" id="skype" name="skype"" />
<input type="text" class="onair" id="twitter" name="twitter" />
<input type="text" class="onair" id="web" name="website" />
<textarea class="onair" id="other" name="other"></textarea>
What I'm wondering is, is there a way to validate by class name instead of by Id? Something that might add the values of each field to check for a count of null or zero?
I've done my searching around, but nothing I've seen actually shows an alert message window that I can customize myself. Also, I'm fairly new to jQuery and JavaScript, so if you could add the opening details and tell me where it goes if it cannot be integrated into my script already, that would be appreciated. Thanks!
You can view the page here...
https://www.itsjustgenoj.com/wp-content/test.html
Note: I'm sorry about the CSS. I stripped it all out on the example above.
Here's Something to validate them fields.
var all = document.querySelectorAll(".onair");
var supplied = 0;
for(var i = 0;i < all.length;i++){
var input = all[i];
if(input.value.length > 0)
{
//get the value by "input.value"
supplied++;
}
}
if(supplied < 1){ alert("Your Message Here"); }
else{
//do whatever after
}
function validate(join)
{
//
// Check for a first name.
//
if (join.fname.value.length > 0)
{
// do more validation if you want
return true;
}
//
// Check for a last name.
//
else if (join.lname.value.length > 0)
{
return true;
}
//
// Check for an e-mail address.
//
else if (join.email.value.length >0)
{
if (join.email.value.length < 5)
{
alert("An email address is required to proceed.");
join.email.focus();
return false;
}
else if (join.email.value.indexOf("#",".") == -1)
{
alert("A valid e-mail address is required to proceed.");
join.email.focus();
return false;
}
else
{
return true;
}
}
// It continues.
else if(join.fname.value.length == 0)
{
alert("Please enter your first name.");
join.fname.focus();
return false
}
else if(join.lname.value.length == 0)
{
alert("Please enter your last name.");
join.lname.focus();
return false
}
// It continues.
} End function
I presume you want to us your validate method with your join form passed as an argument.
If yes you can use querySelectorAll to get your inputs
function validate(join) {
onairInputs = join.querySelectorAll('.onair')
onairInputs.forEach((x) => console.log(x.value))
}
I see that you have some default values in your fields so you will want some custom logic there, as checking that value is simply empty will not work.
The following validation code was handed to me and it just looks so repetative. How could I learn from his example on how to reduce the duplicate processes that occur for each input field that is being validated below....? I want to be more efficient with JavaScript, not repeat the same functions over and over again just because a form adds on a new input element...
function isRequired(){
firstNameRequired();
lastNameRequired();
stateRequired();
gradYearRequired();
relationshipRequired();
birthdayRequired();
}
function firstNameRequired(){
var firstName = document.forms['subscribeForm']['First Name'].value;
if (firstName == null || firstName ==''){
alert('Please enter your first name.');
document.subscribeForm.elements['First Name'].style.backgroundColor='yellow';
return false;
}
}
function lastNameRequired(){
var lastName = document.forms['subscribeForm']['Last Name'].value;
if (lastName == null || lastName ==''){
alert('Please enter your last name.');
document.subscribeForm.elements['Last Name'].style.backgroundColor='yellow';
return false;
}
}
function stateRequired(){
var state = document.forms['subscribeForm']['State'].value;
if (state == null || state ==''){
alert('Please enter your state of residence.');
document.subscribeForm.elements['State'].style.backgroundColor='yellow';
return false;
}
}
function gradYearRequired(){
var gradYear = document.forms['subscribeForm']['Graduation Year'].value;
if (gradYear == null || gradYear ==''){
alert('Please enter your graduation year.');
document.subscribeForm.elements['Graduation Year'].style.backgroundColor='yellow';
return false;
}
}
function relationshipRequired(){
var relationship = document.forms['subscribeForm']['ABC Link Relationship'].value;
if(relationship == null || relationship == ''){
alert('Please enter your relationship to ABC.');
document.subscribeForm.elements['ABC Link Relationship'].style.backgroundColor='yellow';
return false;
}
}
function birthdayRequired(){
var birthDay = document.forms['subscribeForm']['Birthdate'].value;
if(birthDay == null || birthDay == ''){
alert('Please enter your birthday.');
document.subscribeForm.elements['Birthdate'].style.backgroundColor='yellow';
return false;
}
}
...
<input type="submit" class="submitBtn" value="" onclick="isRequired()" />
Also, I have the flexibility to work in jQuery if need be.
Detect what parts in your code are repetitive and what parts do change from field to field. For example, you could create a function that takes two parameters: the field name and its label.
function validateRequiredField(name, label)
{
var value = document.forms['subscribeForm'][name].value;
if (value == null || value == '') {
alert('Please enter your ' + label);
document.forms['subscribeForm'][name].style.backgroundColor = 'yellow';
return false;
}
}
Then you can just call this function passing the name and the label as parameter:
validateRequiredField('First Name', 'first name');
validateRequiredField('ABC Link Relationship', 'relationship to ABC');
// ...
Keep in mind that these validations should be done also in server side, because someone can just disable JavaScript and send your form skipping your client side validation functions.
Because the only data being passed is the object and the alert message, instead of a whole custom function, use a single function with object and message params.
function isRequired(){
required(document.forms['subscribeForm']['First Name'],'first name');
required(document.forms['subscribeForm']['Last Name'],'last name');
required(document.forms['subscribeForm']['State'],'state of residence');
required(document.forms['subscribeForm']['Graduation Year'],'graduation year');
required(document.forms['subscribeForm']['ABC Link Relationship'],'relationship to ABC');
required(document.forms['subscribeForm']['Birthday'],'birthday');
}
function required(object,message){
if (!obj) {
alert('Please enter your '+message);
obj.style.backgroundColor='yellow';
return false;
}
return true;
}
First of all I would recommend to use IDs to read out the form fields:
<input type="text" id="firstname" />
This allows you to use jQuery('#firstname') to select this input field.
Second, here's how I'd go about the task of making the code smaller:
What are you trying to do here?
You always read some value from the form (depending on an ID of sorts).
Then you check if that value is null.
If the value is not set you want to display an error message (depending on the ID again).
And you also want to mark the field that was missing and then return false.
So I'd code a function that does exactly that:
// function having a parameter for the ID and the custom error message
function checkFormField(fieldID, errorMsg) {
// read value from field using jquery
value = $(fieldID).value();
// check for null or empty
if (value == null || value == '') {
// display custom error message
alert(errorMsg);
// change color of field using jQuery
$(fieldID).css('background', 'yellow');
return false;
}
}
Now you can reuse this function for every field you want to check. The new isRequired method would look like this:
function isRequired(){
checkFormField('#firstname', 'Please enter your first name.');
checkFormField('#lastname', 'Please enter your last name.');
// and so on...
}
Note that this example would require name attributes that can be used as identifiers (no spaces)
<input name="first_name" type="text" />
<input name="last_name" type="text" />
js:
function validateRequired(slug, field){
// test for passing condition
if (field.value !== null && field.value !== '') {
return true;
}
else {
alert('Please enter your ' + field.str);
}
return false;
}
/**
* Validate a form using a ruleset object
*
*/
function validateFields(ruleset, form){
var field = {};
var errors = 0;
// Loop though the ruleset
for(var index in ruleset) {
//
if (ruleset.hasOwnProperty(index)) {
field = ruleset[index];
// check if input exists
if (form[index]){
field.value = form[index].value
}
if (ruleset[index].required) {
if (!validateRequired(field)){
errors++;
field.invalid = true;
}
}
// you could add more rules here...
}
}
return errors === 0;
}
var valid = validateFields({
first_name : {
required : true,
str: 'first name'
},
last_name : {
required : true,
str: 'last name'
}
// ...
}, document.forms['subscribeForm']);
this is what is my java script function :
function issueOrReturn() {
var functiontype = document.getElementById("functiontype").value;
alert("functiontype : "+functiontype);
if (functiontype=="issueTempcard") {
alert("1111111111111111111111111");
var empid = document.getElementById("empid").value;
var tempcardnumber = document.getElementById("tempcardnumber").value;
var dateofissue = document.getElementById("dateofissue").value;
if(empid.length==0) {
alert("Please enter Employee ID ");
return false;
}
if(tempcardnumber.length==0) {
alert("Please enter Card Number ");
return false;
}
if(dateofissue.length==0) {
alert("Please enter Date of issue ");
return false;
}
if(empid.length > 0 && tempcardnumber.length > 0 && dateofissue.length > 0) {
document.forms["frmTempcard"].submit();
} else {
alert("Please enter Employee ID and and Card Number and Date of issue ");
return false;
}
}
if (functiontype == "returnTempCard") {
alert("222222222222222222222222222222");
var empid = document.getElementById("empid").value;
var dateofreturn = document.getElementById("dateofreturn").value;
if (empid.length == 0) {
alert("Please enter Employee ID ");
return false;
}
if (dateofreturn.length == 0) {
alert("Please enter Date of return ");
return false;
}
if (empid.length > 0 && dateofreturn.length > 0) {
document.forms["frmTempcard"].submit();
} else {
alert("Please enter Employee ID and Date of return ");
return false;
}
}
}
here the functiontype is : issueTempcard the alert is printed but it is not getting in the if loop of issueTempcard hence the form is not submitted,
also please advise me whether the following way is correct to submit the form :
if (empid.length > 0 && tempcardnumber.length > 0 && dateofissue.length > 0) {
document.forms["frmTempcard"].submit();
} else {
alert("Please enter Employee ID and and Card Number and Date of issue ");
}
kindly provide me some help so that i can do it.
Regards,
Both your function definitions miss their closing } character.
Because of this, they are not executed (because the javascript interpreter fails to read your entire function)
This JsFiddle shows your code up and running without a hitch.
All i did is add the }
To help you debug your JS code, try using Firebug, which can show you where you went wrong ;)
Your way of submitting forms looks fine to me, but is also missing the trailing }