What does "/^\s*$/" mean in this javascript? - javascript

I have this javascript that works well in my PDF form to set a field as required if another field contains data. However, I want to have it ignore a value of "0.00" for the test. But I do not know what /^\s*$/ means let alone how to alter the script for my condition.
var rgEmptyTest = /^\s*$/;
// t is the value to be tested and f is the field to set accordingly
function testMyField (t, f) {
if (rgEmptyTest.test(t)) {
this.getField(f).required = false;
} else {
this.getField(f).required = true;
}
}
Thank you!

In your piece of code there is a function that uses regex
A javaScript regExp reference for you.
Thanks #j08691 for the link that explains and let you test the regex used (regexr.com/3rf9u).
You can change your code like this to make a logical exception
var rgEmptyTest = /^\s*$/;
var rgTest = /0.00/;
// t is the value to be tested and f is the field to set accordingly
function testMyField (t, f) {
if (rgEmptyTest.test(t) || rgTest.test(t)) {
this.getField(f).required = false;
} else {
this.getField(f).required = true;
}
}
I guess it should work

\s means space
* Means any number
" " This is empty
" " This too

I think I got this to work:
var rgEmptyTest = /^\s*$/;
var rgTest = /^[0\.00]$/;
// t is the value to be tested and f is the field to set accordingly
function testMyField (t, f) {
if (rgEmptyTest.test(t) || rgTest.test(t)) {
this.getField(f).required = false;
} else {
this.getField(f).required = true;
}
}
Thank you #Higor Lorenzon and #j08691!

Related

If statement not executing correct code?

So I am trying to develop a Tic Tac Toe game for practice with javascript but I've hit a roadblock. I have an if statement that should be returning true but it isn't. Here is a sample.
var game = true;
var x = 'X';
var o = 'O';
var blank = '';
var turn = x;
var board = [blank, blank, blank,
blank, blank, blank,
blank, blank, blank];
function write() {
$('td').click(function() {
//Making sure that the block that was clicked can only be clicked once
var id = $(event.target).attr('id');
var digit = parseInt(id.slice(-1));
//check to see of the block has been clicked on
if (board[digit] = blank) {
board[digit] = turn;
$(board[digit]).html(turn.toUpperCase());
if (turn = x) {
turn = o;
} else if (turn = o) {
turn = x;
}
} else {
alert("That box has already been clicked on!")
}
});
}
You have two issues at first glance.
First, event is undefined. Define it as a function parameter in your .click call.
$('td').click(function(event) { /* rest of the code */ }
Second, as Pointy commented, = is for assignment, == and === are meant for comparisons.
Thus
if (board[digit] = blank) { /**/ }
needs to be
if (board[digit] === blank) { /**/ }
Regarding the difference between == and === you can get more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Short version, prefer === unless you're absolutely sure you know what you're doing and want to explicitly use ==.
if (board[digit] === blank) {
^^

Make a function only run once (Javascript)

So I'm trying to create a function which changes the 0 slot of an array to an input value. However I want this function to only be able to run once. How do I do this, any help is greatly appreciated thanks.
function submitForm() {
$('#inputForm').submit;
if ($("#inputValue").val() != inputException) {
charSetName();
$("#inputValue").val("");
}
$("#inputValue").val("");
}
function charSetName() {
var nameSet = false;
if (nameSet == false) {
nameSet = true;
charDetails[0] = $("#inputValue").val();
document.getElementById("name").innerHTML = "<li id='name''>Name: " + charDetails[0] + "</li>";
}
}
This is an old question but I was brought here because I needed something similar.
To anyone who comes next time, here was what I eventually did:
I simply declared a variable with an initial count of 0.
Then every time my function runs, it auto increases.
The code I want to run once just checks if the count is 1, then it runs. If not, it doesnt.
Like this:
let count = 0;
count === 1 ? doSomething : doNothing
count++
Does it help?
Try this, I have defined isFunctionCalled:Boolean variable for handle it.
var isFunctionCalled = false;
function submitForm() {
$('#inputForm').submit;
if ($("#inputValue").val() != inputException) {
if (!isFunctionCalled) {
charSetName();
}
$("#inputValue").val("");
}
$("#inputValue").val("");
}
function charSetName() {
var nameSet = false;
if (nameSet == false) {
nameSet = true;
charDetails[0] = $("#inputValue").val();
document.getElementById("name").innerHTML = "<li id='name''>Name: " + charDetails[0] + "</li>";
}
isFunctionCalled = true;
}
Mind the executed variable:
var something = (function() {
var executed = false;
return function () {
if (!executed) {
executed = true;
// do something
}
};
})();
There are a lot of ways to do this.
Just a simple way is to set a flag value.
if(flag){
//your code here...
flag = !flag;
}
SO, if the value of the flag is 1 at first it will work. Then as the flag value is changed to 0, then the next time it is called, it will not be invoked, as flag is 0.

Validate breeze complex-type without validate the entire entity

When you want to validate breeze-entity you write:
this.entityAspect.validateEntity()
But what about if I want to fire validations only for complex-type, without fire the entire-entity validations?
complexType.complexAspect not have method validateEntity.
So, what should I do?
Edit after I saw Jay answer:
I tried to use method validateProperty.
But the result was that it always returns true, becouse it not check each one of the properties.
So, I tried to call method validateProperty several-times, each time for other field of the complexType. It give me boolian-result of valid/not valid, but not update the validation-errors.
Here is the code that I tried after I saw Jay answer, but it is not help:
validateSingleField(myComplexProertyName);
first version of validateSingleField function: (the result was that it always returns true, becouse it not check each one of the properties)
function validateSingleField(object, fieldName) {
var entityAspect = object.entityAspect;
var objectType = object.entityType;
var prop = objectType.getProperty(fieldName);
var value = object.getProperty(fieldName);
if (prop.validators.length > 0) {
var context = { entity: entityAspect.entity, property: prop, propertyName: fieldName };
if (entityAspect._validateProperty(value, context)) {
return true;
}
return false;
}
}
second version:(It give me boolian-result of valid/not valid, but not update the validation-errors.)
function validateSingleField(object, fieldName) {
var aspect = object.entityAspect || object.complexAspect;
var entityAspect = object.entityAspect || object.complexAspect.getEntityAspect();
var objectType = object.entityType || object.complexType;
var prop = objectType.getProperty(fieldName);
if (prop.isComplexProperty) {
var isOk;
objectType.getProperties().forEach(function (p) {
isOk = isOk && validateSingleField(object[fieldName](), p.name)//writing 'object[fieldName]()' - is for send the entire complexType of the entity
});
return isOk;
}
else {
{
var value = object.getProperty(fieldName);
if (prop.validators.length > 0) {
var context = { entity: entityAspect.entity, property: prop, propertyName: fieldName };
if (entityAspect._validateProperty(value, context)) {
return true;
}
return false;
}
}
}
}
There is no separate method to validate a complex type because the validation results are all part of the 'parent' entity. Complex type properties are considered part of the entity, not independent entities.
What you can do is call validateProperty on the 'complex' property of the parent entity.

save variables in local storage and then compare

Due to the site I am working on I need to first store some variables and then compare them.
I can't get my fiddle to work if my values are indeed equal. I have never used local storage before so not sure if I am doing it correctly.
Fiddle is http://jsfiddle.net/ktcle/QuLub/2/
I have just added in the values in the divs so that it is easy to see what they are and won't be in the code.
var userID = user(2, 7),
playerID = player(14),
savedUserid,
savedUPlayerid;
function user(a, b) {
return a * b
}
function player(a) {
return a
}
function saveData(x) {
localStorage.setItem('userID', x);
}
function saveData(x) {
localStorage.setItem('playerID', x);
}
savedUserid = parseInt(localStorage.getItem('userID'));
savedPlayerid = parseInt(localStorage.getItem('playerID'));
if (typeof savedUserid === typeof savedPlayerid) {
alert (true)
}
else {
alert (false)
}
There were a few problems... you werent saving the values, and you were comparing typeof instead of the actual values (as someone else pointed out). Anyway, this is working:
http://jsfiddle.net/QuLub/7/
var userID = user(2, 7),
playerID = player(14),
savedUserid,
savedUPlayerid;
function user(a, b) {
return a * b
}
function player(a) {
return a
}
function saveData(type, value) {
localStorage.setItem(type, value);
}
saveData('userID', userID);
saveData('playerID', playerID);
console.log(localStorage.getItem('userID'));
savedUserid = parseInt(localStorage.getItem('userID'));
savedUPlayerid = parseInt(localStorage.getItem('playerID'));
if (savedUserid === savedUPlayerid) {
alert (true)
}
else {
alert (false)
}
document.getElementById("user").innerHTML = savedUserid;
document.getElementById("player").innerHTML = savedUPlayerid;
The first and main problem I notice is that you never call the saveData function. Also, as you can see, you have 2 functions with the same name, so they will just replace one another.
function saveData(x) {
localStorage.setItem('userID', x);
}
function saveData(x) {
localStorage.setItem('playerID', x);
}
Because of this,
localStorage.getItem('userID')
and
localStorage.getItem('playerID')
are both null.
The second mistake is that you misspelled: savedPlayerid as savedPlayrerid.
Working jsFiddle with the modifications: http://jsfiddle.net/QuLub/3/

in angular-ui-bootstrap (v.0.10.0) Datepicker - how do i disable single day(s) by date (or array of dates)?

I've searched everywhere for longer than i would care to admit, and can not find an answer to this question. the documentation here - http://angular-ui.github.io/bootstrap/#/datepicker - says...
date-disabled (date, mode)
(Default: null) : An optional expression to disable visible options based on passing date and current mode (day|month|year).
and in the HTML markup all of the examples show this in the code as an attribute on the input...
date-disabled="disabled(date, mode)"
i need to know what to do in my JavaScript to get this actually functioning. an example for a single day and an example for passing an array of dates would be greatly appreciated.
thanks in advance...
The markup of
date-disabled="disabled(date, mode)"
means that in your scope you would need to have a function named disabed that accepts two arguments, date and mode, which you would use to determine if that date should be disabled.
Here is a clearer example for you. Make the markup be
date-disabled="shouldDateBeDisabled(date, mode)"
Then in your Controller you would need to attach a function named shouldDateBeDisabled to the $scope where you would put your logic.
var datesAreEqual = function(date1,date2) {...};
var dateIsInArray = function(date,arrayOfDates) {...};
var someSingleDateToDisable = ...;
var arrayOfDatesToDisable = [...];
$scope.shouldDateBeDisabled = function(date, mode) {
// your own logic to determine if a date should be disabled
if (datesAreEqual(date,someSingleDateToDisable) {
return true;
}
if (dateIsInArray(date,arrayOfDatesToDisable) {
return true;
}
return false;
};
I had a similar requirement in my project to enable days by giving an array of date objects, i have over ridden the default controller in my project.
This is what i did
In "controller('DatepickerController')" under module('ui.bootstrap.datepicker')
i have added config and a method
this.enabledDays = getValue($attrs.enabledDays, dtConfig.enabledDays);
this.toBeDisabled = function (date, mode) {
var currentMode = this.modes[mode || 0];
var flag = false;
for (var i = 0; i < this.enabledDays.length; i++) {
if (!currentMode.compare(date, this.enabledDays[i])) {
flag = true;
break;
}
}
return flag;
}
then i changed the following predefined method
this.isDisabled = function (date, mode) {
var currentMode = this.modes[mode || 0];
return ((this.enabledDays && !this.toBeDisabled(date, mode)) ||
(this.minDate && currentMode.compare(date, this.minDate) < 0) ||
(this.maxDate && currentMode.compare(date, this.maxDate) > 0) ||
($scope.dateDisabled && $scope.dateDisabled({date: date, mode: currentMode.name})));
};
And in the link function under this directive directive('datepicker', ...
I added
var enabledDays = datepickerConfig.enabledDays;
if (attrs.enabledDays) {
scope.$parent.$watch($parse(attrs.enabledDays), function (value) {
enabledDays = value ? value : null;
datepickerCtrl.enabledDays = enabledDays;
refill();
});
}
And in the "scope.move" function inside the link function, i added
if (typeof datepickerCtrl.onChange != "undefined") {
datepickerCtrl.onChange(selected);
}
as you can see below
scope.move = function (direction) {
var step = datepickerCtrl.modes[mode].step;
selected.setMonth(selected.getMonth() + direction * (step.months || 0));
selected.setFullYear(selected.getFullYear() + direction * (step.years || 0));
if (typeof datepickerCtrl.onChange != "undefined") {
datepickerCtrl.onChange(selected);
}
refill();
};
Now the datepicker is modified
In the HTML markup
<datepicker enabled-days="enabledDays" datepickerConfig="datepickerOptions"></datepicker>
where "enabledDays" is an array you can define in the scope
Worked well for me without any problems yet
Hope this helps you :)

Categories

Resources