I've got some form verification code that doesn't seem to be working correctly, and I can't figure out why.
function isTextFieldEmpty(textField){
//return true or false depending on whether or not there is any text in the field
console.log("Checking to see if the current field is empty...");
var val = textField.value; //val is the text from the current field
console.log("The current value of 'val' is: " + val);
if(val.length < 1){
return true;
}else{
return false;
}
}
The error I get is: "Uncaught TypeError: Cannot read property 'length' of undefined". Sure enough, my console log says that the value of 'val' is undefined.
I'm sure I'm missing something, but I'm still learning JS and can't figure out what it is. Any suggestions?
Edit: Here is what I'm passing to the function:
var uName = document.getElementById("unionname");
var noUnionName = isTextFieldEmpty(uName);
'unionname' is the id of the texfield that I'm trying to validate. Here is the relevant HTML:
<div class="formBox">
<label for="unionname">Union Name</label>
<input type="text" name="unionname" id="unionname" value="" class="wide"/>
<span class="feedback good">Sample good message</span>
</div>
You are declaring var val locally in that function. Try declaring it globally by putting it at the top of your script; don't need to set it, just declare it.
I've gotten it working. Seems that the validation function was fine; the problem was in the way I was calling it.
window.onload = justDoIt;
function justDoIt() {
var uName = document.getElementById("unionname");
uName.onblur = function(){
clearMessages(uName); // clear out old feedback for this field
var noUnionName = isTextFieldEmpty(uName);
This is how I ended up calling the function.
Ironically, it seems that the faulty .onblur code that I left out of my previous example may have been the cause of my problem. But I'm really not sure.
Related
Issue
Keep getting 'undefined' as returned google tag manager variable.
Description
I am trying to write a custom javascript variable to pull 'data-name' IF the 'data-form-title' returns ""
I have a website I am trying to tag and need to grab the form names. The problem came into play where some of the forms' names come back as "" so I wanted to use IF/Then logic to choose another attribute if the first came back empty.
Form that has proper form title https://www.mcgeetoyotaofclaremont.com/popup-availability
Form that has empty "" form title ('text yourself a link') https://www.mcgeetoyotaofclaremont.com/vehicle-details/new-2020-toyota-yaris-hatchback-le-claremont-nh-id-33375400#
What I've Tried
I've tested both querySelectors and they both work on their own. It's when I try to make the IF condition that I run into issues.
I have also tried var answer = 'Unknown' and then replacing the variable with either formtitle or datatitle, depending on the conditional, so that the script only had 1 return in the function.
For the life of me this seems simple and when I cross-check other examples (such as taking the name out of the function) it seems it should work fine.
Current Code
function() {
var formtitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-form-title'].nodeValue;
var datatitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-name'].nodeValue;
if (formtitle != ""){
return formtitle;
} else {
return datatitle;
}
}
When I try to run your current code on your forms I get an error: Uncaught TypeError: Cannot read property 'nodeValue' of undefined. This error would make your GTM function return undefined every time.
the problem seems to be this line of code:
var datatitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-name'].nodeValue;
there is no data-name attribute. So you either need to make sure you are trying to access the right attribute or you can simply surround your variables in try-catch blocks like this:
function() {
var formtitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-form-title'].nodeValue;
var datatitle = '';
try{
datatitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-name'].nodeValue;
}catch(err){}
if (formtitle != ""){
return formtitle;
} else {
return datatitle;
}
}
I'm new to angularjs and am trying to use the angucomplete-alt to allow the user to search for worker names. The search works great, but when I try to clear the input box after the user selects a result the box clears but I get this error message...
TypeError: Unable to get property 'originalObject' of undefined or null reference
at $scope.nameSelected (..Worker.php:498:3)
at callOrAssign (..angucomplete-alt.js:167:11)
at Anonymous function (..angucomplete-alt.js:124:11)
at Scope.prototype.$broadcast (..angular.js:18487:15)
at $scope.deleteRow (..Worker.php:471:6)
at fn (Function code:2:153)
at callback (..angular.js:26994:17)
at Scope.prototype.$eval (..angular.js:18161:9)
at Scope.prototype.$apply (..angular.js:18261:13)
at Anonymous function (..angular.js:26999:17)
Everything seems to work fine, but I hate getting a huge error every time.
this is the box
<angucomplete-alt id="workerName"
placeholder="Name"
pause="100"
minlength="2"
selected-object="nameSelected"
remote-url="Suggest_Name.php?term="
remote-url-data-field=""
title-field="value"
input-class="form-control">
</angucomplete-alt>
and this is the clear command
//clear the autocomplete text box
$scope.$broadcast('angucomplete-alt:clearInput','workerName');
thanks to a user's question I think I've figured it out. It looks like the nameSelected function fires when the autocomplete is cleared. Here's nameSelected..
//autocomplete callback function
$scope.nameSelected = function ($item){
if($item != undefined){ //I just added this
//console.log($item.originalObject);
$scope.worker_new.Emp_Name = $item.originalObject.lastname + ', ' + $item.originalObject.firstname;
$scope.worker_new.PDCWorker_EID = $item.originalObject.UWIdNbr;
$scope.worker_new.PCA_Option = $item.originalObject.pca_option;
}
}
adding the check to see if '$item' is undefined has solved my error problem.
function() {
var id1 = document.getElementById("usrEmailId").value
var id2 = document.getElementById("usrEmailIdSecondary").value
var id3 = document.getElementById("emailId").value
}
Here, on a HTML page, I have Email Id capture field. There are two pages and one page has only the element usrEmailId and usrEmailIdSecondary and the other page has the elements usrEmailId and emailI. So what will happen to variable id3 in case of first page. What will be stored in it? (NULL, undefined, or empty)?
If the element doesn't exist and getElementById returns null, nothing will get stored at all because trying to access the .value property on null will throw an exception before.
What will be stored in it?
Short answer: Nothing.
It will throw error as something like "can't get value of null" and code execution stops at this place.
var id1 = document.getElementById("usrEmailId").value; // <---if doesn't exist
console.log('Log it if id1 is null.'); // <---it won't happen
An error gets generated on the javascript console. Check this code snippet
function foo() {
var id1 = document.getElementById("Email1").value
console.log(id1);
}
<body>
<input type="text" id="Email">
<input type="text" id="pwd">
<button onClick=foo()>Try</button>
</body>
Try running the code, you'll find Cannot read property 'value' of null appearing on the console whenever a getElementById("Email1").value is called as id Email1 is not present in the page.
Open developer tools/Inspect > Console if console output doesn't appear on screen.
I am debugging a javascript/html5 web app that uses a lot of memory. Occasionally I get an error message in the console window saying
"uncaught exception: out of memory".
Is there a way for me to gracefully handle this error inside the app?
Ultimately I need to re-write parts of this to prevent this from happening in the first place.
You should calclulate size of your localStorage,
window.localStorage is full
as a solution is to try to add something
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
var storageIsFull = function () {
var size = localStorageSpace(); // old size
// try to add data
var er;
try {
window.localStorage.setItem("test-size", "1");
} catch(er) {}
// check if data added
var isFull = (size === localStorageSpace());
window.localStorage.removeItem("test-size");
return isFull;
}
I also got the same error message recently when working on a project having lots of JS and sending Json, but the solution which I found was to update input type="submit" attribute to input type="button". I know there are limitations of using input type="button"..> and the solution looks weird, but if your application has ajax with JS,Json data, you can give it a try. Thanks.
Faced the same problem in Firefox then later I came to know I was trying to reload a HTML page even before setting up some data into local-storage inside if loop. So you need to take care of that one and also check somewhere ID is repeating or not.
But same thing was working great in Chrome. Maybe Chrome is more Intelligent.
While developing a web application I want to perform certain validation check and only after sucesssful validation I need to post the form and redirect control to next page.
JavaScript code:
function fnCheckEmptyField()
{
var strDomain = document.getElementsByName("txtIIDN").value;
if (strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML = "";
document.getElementById("lblValidityStatus").innerHTML = "Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
Relevant HTML code:
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField()">
<input type="text" id="txtIIDN"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
The line onsubmit="return fnCheckEmptyField()" shows an error Cannot return from outside a function or method and after execution of the JavaScript function form is getting submitted regardless the text field is blank or not.
I have placed alerts inside if condition and it is sure that if field is empty function returns false.
I don't know what's wrong with my code and why this errors with Cannot return from outside a function or method.
What's the cause and how can I solve it?
the line onsubmit="return fnCheckEmptyField()" showing an error Cannot return from outside a function or method
That's specific to Eclipse. Eclipse is wrong here, that line is perfectly fine. Just ignore the Eclipse error. If you want, you can always disable its JS validation.
and after execution of the java script function form is getting submitted regardless the text field is blank or not.
That's because your JavaScript function is wrong. You've 2 mistakes in your JS code.
The getElementsByName() call is incorrect.
var strDomain = document.getElementsByName("txtIIDN").value;
To retrieve an element by ID, you need getElementById().
var strDomain = document.getElementById("txtIIDN").value;
Empty values are not null, but just empty string.
if (strDomain == null)
You need to check its length instead.
if (strDomain.length == 0)
Or just make use of JS boolean magic.
if (!strDomain)
By the way, the line document.getElementById("lblValidityStatus").innerHTML = ""; is unnecessary in this code.
remove the "return" from onsubmit attribut
your code should look like this
<form action="Result.jsp" name="validityCheck" onsubmit="fnCheckEmptyField()">
<input type="text" id="txtIIDN"/>
</form>
hope this solve your problem :-)
Also,
var strDomain= document.getElementsByName("txtIIDN").value;
should be
var strDomain= document.getElementById("txtIIDN").value;
The text field has an id, not a name
Remove Action from Form Tag.
function fnCheckEmptyField()
{
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML="";
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
}
else
{
window.navigate("top.jsp");
}
}
I'm no javascript expert but I think you should lose the return keyword in your onsubmit parameter in the HTML; like below:
onsubmit="fnCheckEmptyField()"
edit: sorry was posting concurrently with previous answer