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?
Related
I am trying to validate two input fields in my form using javascript. But my functions checks only one value for null or empty string. It submits the form if the other value is empty. Why?
function checkFieldEmpty()
{
var a=document.forms["verifyURN"]["urnNumber"].value;
var b=document.forms["verifyURN"]["urnDate"].value;
if (a==null || a=="", b==null || b=="") //b field validates here, not a..?
{
return false;
}
return true; //function returns true even if a is empty..?
}
//Below function is called when submit button pressed in my form
function verifyURN()
{
if(checkFieldEmpty())
{
document.verifyURN.rDoAction.value = "<%=Constant.myPage%>";
document.verifyURN.submit();
}
else{
alert("Mandatory fields empty");
return false;
}
}
...
<form name="verifyURN"...
try add
alert(a.length);
alert(b.length);
before your
if (a==null || a=="", b==null || b=="") //b field validates here, not a..?
{
and you will have a better picture of what criteria to check.
I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>
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']);
I have a <form> Its default property is submitted=false; and I have a statement
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}else{
//missing piece
}
})
So when the user clicks the button and the above statement is not satisfied, I want to add onsubmit="submitted=true;" in my <form> and make it something like this <form onsubmit="submitted=true;".
If I don't get you wrong, you want to run that check and if it went well you want to set a variable named submitted to TRUE, and set it to FALSE otherwise.
If so, you could do it this way:
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
});
if(empty > 0) submitted = false;
else submitted = true;
}
If that's not the case. If you wanted to show an error if there's an empty field and prevent the form from submitting if there's an empty field, so you should do it this way:
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
});
return empty == 0;
}
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 }