Only first part of Javascript function being called - javascript

I'm having problems with this function I've made, the first part is called fine but after the first if statements nothing else is being called. I've used JSfiddle, but it doesn't indentify a serious problem.
I usually work with PHP not JS so I'm wondering if there is something simple I am missing here?
function validatequestion(form){
var e = document.getElementById("chooseqtype");
var strQtype = e.options[e.selectedIndex].value;
if(strQtype == "default"){
alert("Please select a question type");
return false;
}
if(strQtype == "textquestion"){
fail = validatetextq(form.textquestiondesc.value)
if(fail == "") return true
else {
alert(fail);
return false;
}
}
if(strQtype == "videoquestion"){
fail = validatevideoq(form.videoquestiondesc.value)
if(fail == "") return true;
else {
alert(fail);
return false;
}
}
//everything above works, after this point nothing seems to get called
var a = document.getElementById("chooseatype");
var strAtype = a.options[a.selectedIndex].value;
if(strAtype == "textanswer"){
//get the value of the number of text answers select box
var t = document.getElementById("choosetextnumber");
//put the value in variable strQtype
var strTextno = t.options[t.selectedIndex].value;
if(strTextno == "2tanswers"){
fail = validatetexta1(form.textanswer1.value)
fail += validatetexta2(form.textanswer2.value)
if(fail == "") return true;
else {
alert(fail);
return false;
}
}
}
}

If strQtype can only be one of the 3 values you are testing for then there is no way you can ever get to the second part of your code because you always return from each of those if statements.
EDIT:
What you need to do is not return when fail == "". Since you're just returning true I assume you don't need to return a value, just verify that the validation was successful. What you should do then is only test for failure, e.g. if (! fail=="" ) (syntax is prob wrong, javascript is not my first lang.) and in that case do your alert.
Or you could always just write 3 different functions, one to test each menu item, which is what I would probably do.

Related

Function returning undefined, I know it's to do with the non-return but I am struggling to solve

I have a function that takes a variable called (compactArray) (there is another function to produce and return a compact array that works fine)
I know it's because my function is not returning any value, but I am struggling to solve the return = undefined.
the code is below
let a = null;
let b = null;
let operand = null;
let total = null;
function testGrab (compactArray) {
if(compactArray == typeof(Number) && a == null) {
return a = compactArray;
} else if (compactArray == typeof(Number) && a !== null){
return b = compactArray;
} else if (compactArray == typeof(String)){
return operand = compactArray;
}
return total
};
const compactArray = 467;
console.log(testGrab(compactArray));
console.log(a)
I want this function to take the compactArray returned from a different function and assign it to the correct variable a,b,operand.
is this possible, or would I need to make a function to return the relevant if statement, and then create another function to assign the returned value to the correct variable?
I know it's because my function is not returning anything but I am stumped at the moment.
if you want to check whether compactArray's type is a number:
change this statement "if(compactArray == typeof(Number) && a == null)"
to this statement "if("number" == typeof(compactArray) && a == null)"

JQuery not executing defined function in .blur()

I'm very new to JQuery and Javascript in general, and I'm working on a project for school. While I can get everything to work without defining any functions, I want to reduce redundant code.
Here's a bit of what I'm trying to do:
function firstNameChanged() {
var x = document.getElementById("firstName").value;
if (x == null || x == "") {
$("#firstNameError").html(" First name can't be blank!");
}
else {
$("#firstNameError").html("");
}
}
$(document).ready(function(){
$("#firstName").blur(firstNameChange());
}
Yes I'm positive all IDs exist, because the code works when I pass it as:
$("#firstName").blur(function(){
var x = document.getElementById("firstName").value;
if (x == null || x == "") {
$("#firstNameError").html(" First name can't be blank!");
}
else {
$("#firstNameError").html("");
}
})
I've looked up plenty of documentation on Javascript and JQuery syntax, debugged in Chrome, I can't figure it out.
blur expects a function reference as a parameter. firstNameChange() is calling the function immediately. Remove the ()
$("#firstName").blur(firstNameChange);

Global variable setting fails in JavaScript validation

I am getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.
if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.
This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks
Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console

jQuery returning multiple functions doesn't work

I am working a simple form validation and I have 3 functions where I check the input text fields, a select field and 2 radio buttons. For each group I have made a function, so 3 functions.
I have tested the functions on its own and they are working. But if I use them all 3 together at the end of my script, only one of them works.
Can anyone tell me what I need to do?
// Form validation
$(function() {
function wz_validation() {
var ok = true;
$('input[validate="true"]').each(function() {
if($(this).val() == '') {
ok = false;
$(this).addClass('red_border');
}
else $(this).removeClass('red_border');
});
return ok;
}
// Check Bank select box on checkout page
function wz_val_select() {
if($(".payment select")) {
if($(".payment select option:selected").val() == "") {
$(".payment select").addClass('red_border');
return false;
}
else{
$(".payment select").removeClass('red_border');
return true;
}
}
}
function wz_radio_shipping() {
var form = $("#shipping_form");
if(form.length) {
if(form.find('input[name=wz_shipping]:checked').length == 0) {
$("#checkout_shipping").addClass('red_border');
return false;
}
else{
$("#checkout_shipping").removeClass('red_border');
return true;
}
}
}
var wz_form = $('#wz_form1, #wz_form2, #wz_form3, #wz_form7');
$(wz_form).submit(function() {
return wz_validation() && wz_radio_shipping() && wz_val_select();
});
});
&& is a short circuit operator. It prevents the evaluation of b in a && b when a is falsy.
If you want to have all three functions called even when some of them return false, and if you only return boolean values, use &. As & makes 0 or 1, you might want to convert the result to a boolean with !! :
return !!(wz_validation() & wz_radio_shipping() & wz_val_select());
You might also want to write it more explicitly :
$(wz_form).submit(function(e) {
var good = true;
good &= wz_validation();
good &= wz_radio_shipping();
good &= wz_val_select();
if (!good) e.preventDefault();
});

Returning a boolean value in a JavaScript function

I am doing a client side form validation to check if passwords match. But the validation function always returns undefined.
function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}
Please note that the validatePassword is called from a member function of the Form object.
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}
Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}
//result is always undefined
if(result)
{
//do other stuff
}
}
You could simplify this a lot:
Check whether one is not empty
Check whether they are equal
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
You could wrap your return value in the Boolean function
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. #pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean

Categories