I'm new to JavaScript so I apologize if this is simple. I'm passing a couple values to my controller but after, I need to reset the global variables without refreshing the page. My code looks like this:
var userName = null;
var _delegated = false;
function setAddtionalData(value) {
if(value == true) {
userName = "something";
_delegated = value;
}
}
function getAdditionalData() {
return {
username: userName,
delegated: _delegated
};
userName = null; // Does not get hit
_delegated = false; // Does not get hit
}
But variables never get updated. Is there a way to set these without page a refresh?
Code after the return will not be executed. You need to grab the values, clear the variables, and return the grabbed values:
function getAdditionalData() {
var retval = {
username: userName,
delegated: _delegated
};
userName = null;
_delegated = false;
return retval;
}
Those values are never reached since your return statement exits out of the function.
You should save, username and _delegated to temporary variables, set them to null, and then return the object.
return statements are used to exit out of a function, so anything you put after your return statement will not happen.
Related
I have a variable tokens which is used as an OTP.It is also stored in the Session variable. I want that tokens to be accessible in JavaScript. So I created a function to return the variable.
function submitotp() {
var re = new RegExp("^[A-Z]{6}$");
var term = document.getElementById("otpinp").value;
var count = 0;
if (re.test(term)) {
$("#sup2").hide();
$("#sup3").show();
return true;
}
else {
return false;
}
and my returning function is
public string tokens(string token)
{
token = Session["otp"].ToString();
return token;
}
I want to access tokens and check if it matches that of a textbox.
Edit: It is an MVC code.
Put your Session["otp"] into ViewData["otp"] and use it on your view like below
In Controller
ViewData["otp"] = Session["otp"];
In View
#ViewData["otp"]
$.post("#Url.Action("tokens","Citizen")", function (data) {
if (re.test(term) && term == data) {
$("#sup2").hide();
$("#sup3").show();
return true;
}
Used this to access the variable. It worked.
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
I can't seem to get my code to check which user role I've selected from the drop down. I don't often use for this so I'm kind of running into some trouble with it I think. Let me know if I'm missing something? I left the console.log()'s in but they haven't returned anything.
var userRole = "";
if ($('select[name=custom1]').find(':selected').val("") === "Healthcare Practitioner") {
return userRole = "SR-Practitioner";
console.log(userRole);
} else {
return userRole = "SR-Educator";
console.log(userRole);
};
A return statement is an exit point of a function. Everything after the return statement won't be executed. One exception is code that are wrapped in a try finally block. Therefore the console.log won't be executed.
Like #MDeSchaepmeester wrote: a .val(arg) call is a setter not a getter. Please read the documentation of .val(): http://api.jquery.com/val/
if ($('select[name=custom1]').find(':selected').val() === "Healthcare Practitioner") {
return "SR-Practitioner";
} else {
return "SR-Educator";
};
or
var userRole = '';
if ($('select[name=custom1]').find(':selected').val() === "Healthcare Practitioner") {
userRole = "SR-Practitioner";
} else {
userRole "SR-Educator";
};
console.log(userRole);
I made a function which validates a form and works fine but I now want to break it down into 3 separate functions.
I now have a function which is called by the form being submitted which declares some arrays and runs the three functions. When it was all one big function the various if statements that found errors would return false; which would then go back to the form and stop it sending.
However now that I've got functions within a function I can't figure out how to get that message 'false' back to the form.
Below is the function called by the form submit button followed by the main function it calls.
I tried creating an empty variable which is returned instead of false which is then is assigned the value false by the validateSignup function but it didn't work.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
passMatch();
genderCountryCheck()
}
function validateText(formNumber, numberElements, errorSpansArrayName, regexErrorArrayName, regexArrayName)
{
for (x = 0; x<numberElements; x++)
{
var spanName = errorSpansArrayName[x];
var textError = document.getElementById(spanName);
var y=document.forms[formNumber].elements[x];
if (!y.value)
{
errorMessage(0,spanName,x);
return false;
}
if(!regexArrayName[x].test(y.value)){
textError.innerHTML = regexErrorArrayName[x];
return false;
}
}
UPDATE:
Thanks for your responses. I have found a solution that seems to work for me.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var returnValidateText=validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
var returnPassMatch = passMatch();
var returnGenderCountry = genderCountryCheck();
if (returnValidateText || returnPassMatch || returnGenderCountry === false)
{
return false;
}
else{
return true;
}
}
If you call the function it returns a value
var formIsValid = function validateText(....)
should do the trick.
function validateSignup()
{
// Declaring Arrays (deleted array contents)
var errorSpansArray=[whatever];
var regexErrorArray=[whatever];
var regexArray=[whatever];
var formIsValid = false;
formIsValid = validateText(0,6,errorSpansArray, regexErrorArray, regexArray);
formIsValid = passMatch();
formIsValid = genderCountryCheck()
}
One way is to just check the individual function returns directly and return based on that
if (!validateText(0,6,errorSpansArray, regexErrorArray, regexArray)) {
return false;
}
if (!passMatch()) {
return false;
}
if (!genderCountryCheck()) {
return false;
}
Although it's shorter to use a single conditional
return
validateText(0,6,errorSpansArray, regexErrorArray, regexArray) &&
passMatch() &&
genderCountryCheck();
In javascript return false means false will be returned as value where the method is called. So you need something like
If(validateText()){
return true;
}
And similarly rest of the code.
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