getAttribute() Error - javascript

I am getting an error in firefox about getAttribute not being a function. Below is my code with the error line marked.
var nodeList = document.getElementsByTagName("input");
for(item in nodeList){
try{
if(nodeList[item].getAttribute("type") == "file"){
//ERROR HERE///->var id = nodeList[item].getAttribute("id");
var fileSelector = document.getElementById(id);
document.getElementById(id).addEventListener("change",function(e){
if(e){
e.preventDefault();
}
if (fileSelector.files) {
window.file = fileSelector.files[0];
} else {
window.file = fileSelector.value;
}
readData();
});
}
}catch(e){}
}

Try like this :
var nodeList = document.getElementsByTagName("input");
var max = nodeList.length;
for(var i=0; i<max ; i++){
try{
if(nodeList[i].getAttribute("type") == "file"){
//ERROR HERE///->var id = nodeList[item].getAttribute("id");
var fileSelector = document.getElementById(id);
document.getElementById(id).addEventListener("change",function(e){
if(e){
e.preventDefault();
}
if (fileSelector.files) {
window.file = fileSelector.files[0];
} else {
window.file = fileSelector.value;
}
readData();
});
}
}catch(e){}
}

Probably nodeList[item] is not a Node. Use a for loop instead of for..in:
var i, len = nodeList.length;
for(i=0; i<len; i += 1){
try {
if(nodeList[i].getAttribute("type") == "file"){
// ...

See JSFiddle for an explanation
for (item in nodeList)
gives 0, 1 and 2 as the array indices, which is ok.
But then it delivers more properties length, item and namedItem, which aren't DOM elements and don't have a getAttribute() function.
So, as others have already suggested, use a normal for loop.

Related

Sudden error in js to get first element by class

I used this for ages:
function findFirstChildByClass(element, className) {
var foundElement = null, found;
function recurse(element, className, found) {
for (var i = 0; i < element.childNodes.length && !found; i++) {
var el = element.childNodes[i];
var classes = el.className != undefined? el.className.split(" ") : [];
for (var j = 0, jl = classes.length; j < jl; j++) {
if (classes[j] == className) {
found = true;
foundElement = element.childNodes[i];
break;
}
}
if(found)
break;
recurse(element.childNodes[i], className, found);
}
}
recurse(element, className, false);
return foundElement;
}
But suddenly, this line throws an error:
var classes = el.className != undefined? el.className.split(" ") : [];
Uncaught TypeError: el.className.split is not a function
I can't see right now what's wrong.
It's related of the use of svg complex class name. Before refactoring everything, I quickly fixed the issue replacing the wrong line.
if (el.className != undefined && typeof(el.className) === 'string') {
classes = el.className.split(" ")
} else {
classes = []
}
The className property on svg elements is an Object type SVGAnimatedString and therefore doesn't have the split method.

Object doesn't support property or method 'forEach' in IE11

I have a function and it doesn't work in IE11. Display me this error in the forEach. In chrome and firefox work fine. Please help.
Object doesn't support property or method 'forEach'
function someFunction(event) {
var classList = event.currentTarget.classList.toString();
var targetClass = classList.toString().slice(classList.indexOf('open'));
$('button').removeClass('active');
var toOpen = document.getElementsByClassName(targetClass);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
for (var _iterator = toOpen[Symbol.iterator](), _step
; !(_iteratorNormalCompletion = (_step = _iterator.next()).done)
; _iteratorNormalCompletion = true) {
var el = _step.value;
var childPanels = el.querySelectorAll('.fa');
childPanels.forEach(function (child) {
child.classList.toggle('fa-minus');
child.classList.toggle('fa-active');
});
var childPanels = el.querySelectorAll('.panel');
childPanels.forEach(function (child) {
child.classList.toggle('current');
});
}
}
forEach loops aren't supported by IE11, but you can easily get your own forEach :
For example, this :
childPanels.forEach(function (child) {
child.classList.toggle('fa-minus');
child.classList.toggle('fa-active');
});
will do the exact same thing than :
for (let idx = 0; idx < childPanels.length; i++) {
childPanels[idx].classList.toggle('fa-minus');
childPanels[idx].classList.toggle('fa-active');
}

Uncaught TypeError: Cannot read property 'done' of undefined Javascript

Been trying to solve this issue for the past few days. Surprisingly, my checkbox and Localstorage all works but in console, it displays an error "Uncaught TypeError: Cannot read property 'done' of undefined". I have tried my best to solve this issue to make the error go away but no luck. I know I am trying to call the ".done" property that doesn't exist but how do I solve this issue? I have google'd and read all similar questions on SO.
I don't think it's acceptable to ignore this error in console right? Can somebody please guide/help me? Please just JavaScript, no jQuery. Thanks!
The error comes from the function checkAll() and uncheckAll().
function checkAll() {
var getInputs = document.getElementsByTagName("input");
for (var i = 0, max = getInputs.length; i < max; i++) {
if (getInputs[i].type === 'checkbox')
getInputs[i].checked = true;
items[i].done = true;
localStorage.setItem('items', JSON.stringify(items));
}
}
and
function uncheckAll() {
var getInputs = document.getElementsByTagName("input");
for (var i = 0, max = getInputs.length; i < max; i++) {
if (getInputs[i].type === 'checkbox')
getInputs[i].checked = false;
items[i].done = false;
localStorage.setItem('items', JSON.stringify(items));
}
}
My code below:
<script>
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = JSON.parse(localStorage.getItem('items')) || [];
function addItem(e) {
e.preventDefault();
const text = (this.querySelector('[name=item]')).value;
const item = {
text,
done: false
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
this.reset();
}
function populateList(plates = [], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label for="item${i}">${plate.text}</label>
</li>
`;
}).join('');
}
function toggleDone(e) {
if(!e.target.matches('input')) return; //skip unless its an input
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
addItems.addEventListener('submit', addItem);
itemsList.addEventListener('click', toggleDone);
populateList(items, itemsList);
// Challenge: Button: clear all, check all, uncheck all
function checkAll() {
var getInputs = document.getElementsByTagName("input");
for (var i = 0, max = getInputs.length; i < max; i++) {
if (getInputs[i].type === 'checkbox')
getInputs[i].checked = true;
items[i].done = true;
localStorage.setItem('items', JSON.stringify(items));
}
}
function uncheckAll() {
var getInputs = document.getElementsByTagName("input");
for (var i = 0, max = getInputs.length; i < max; i++) {
if (getInputs[i].type === 'checkbox')
getInputs[i].checked = false;
items[i].done = false;
localStorage.setItem('items', JSON.stringify(items));
}
}
function clearItem() {
localStorage.clear();
var element = document.getElementById("plates");
element.parentNode.removeChild(element);
location.reload();
console.log('Items cleared in localStorage');
}
</script>
Because you are initializing the array to empty, if there are no items set in localstorage
const items = JSON.parse(localStorage.getItem('items')) || [];
It is possible that your items[i] could be undefined.
You need to change
items[i].done = false; //similarly for true
to
items[i] = items[i] || {};
items[i].done = false; //or true

JavaScript Check multiple variables being empty

I'm trying the following code:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array('var1','var2','var3');
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
The result here should have been count = 2 because two of the variables are empty but it's always 0. I guess it must something when using if (field_is_empty(name)) because it might not getting the name converted to the name of the actual var.
PROBLEM 2# Still related
I've updated the code as Karthik Ganesan mentioned and it works perfectly.
Now the code is:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
And the problem is that if add a new if statement something like this:
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(name,"test");
}
}
}
It does nothing and I've tested using variableService.setValue('var1',"test") and it works.
PS: The variableService.setValue is a function controlled by the software I don't know exactly what it does I know if use it like mentioned on above line it works.
In your first attempt you used the variable names as strings when you created an array. You need to either use the values themselves:
vars = new Array(var1,var2,var3);
or if you insist to use them by their names, then you need to find them by names when you use them:
if (field_is_empty(window[name])) {
It does nothing
That's not really possible. It could throw an error, or enter the if or enter the else, but doing nothing is impossible. However, since you intended to use the variables by name in the first place (probably not without a reason) and then you intend to pass a name, but it is a value and it does not work as expected, I assume that your initial array initialization was correct and the if should be fixed like this:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]]; //You need the value here
if (field_is_empty(v)) {
count++;
}
}
console.log(count);
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]];
if (field_is_empty(v)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(vars[i],"test");
}
}
}
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
You definitely incorrectly initialize array, you put strings "var1", "var2", "var3" instead of references to strings (variables).
Try this:
vars = new Array(var1,var2,var3);
Your array is wrong
it should be
vars = new Array(var1,var2,var3);
here is the jsfiddle

Firefox javascript error function "undefined" works fine in IE

I'm receiving an error in firefox error console "Error: submitSearchForm is not defined"
this is my code for that function
EDIT: added full code
function submitSearchForm(action,iskeyDown) {
var oneEntered = false;
if(iskeyDown == null || iskeyDown == 'undefined'){
copyAndValidate("dobFrom", "searchCriteria.dob", "date");
copyAndValidate("dobTo", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
}else{
copyAndValidate("dobFrom_date", "searchCriteria.dob", "date");
copyAndValidate("dobTo_date", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom_date", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo_date", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
}
var elements = document.SearchForm.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element != null && element.getAttribute("group") == 'searchCriteria') {
if (!isEmpty(element.value)) {
oneEntered = true;
break;
}
}
}
if (oneEntered)
{
if (validate(document.SearchForm)) {
document.SearchForm.action.value = action;
document.SearchForm.submit();
}
}
else {
alert("<%= bpt.getValue("CCT_ATLEASTONE_MSG") %>");
}
}
button
onclick="<%="submitSearchForm('"+SearchForm.ACTION_SEARCH +"');"%>"
just to say again everything works fine in IE so the code is correct
EDIT: VALIDATION.JS validate()
function validate(thisForm) {
window.event.returnValue = false;
formToValidate = thisForm;
var ret = true;
var validationErrors = new Array();
// get the validateable items
// var validateThese = getValidationItems(thisForm.childNodes);
var validateThese = getValidationItems(thisForm);
//printValidationArray(validateThese);
// validate them
for (var i = 0; i < validateThese.length; i++) {
var validationItem = validateThese[i];
var validationError = validateMe(validationItem);
if (validationError != "") {
validationErrors[validationErrors.length] = validationError;
}
}
// check for validation errors
if (validationErrors.length > 0) {
var errors = "";
for (var j = 0; j < validationErrors.length; j++) {
errors += validationErrors[j] + "\n";
}
alert("Validation Errors:\n" + errors);
ret = false;
} else {
ret = true;
}
return ret;
}
window.event (also referenced as just event) is not a standard global object in JavaScript. It is an IE-only "feature."
See this question.
Try changing the function declaration to:
function submitSearchForm(action, iskeyDown) {
// ...
// { <------------------------------------------------ brace removed
if (validate(document.SearchForm)) {
document.SearchForm.action.value = action;
document.SearchForm.submit();
}
// } <----------------------------------------------- brace removed
}
Braces in JavaScript do not work the same way as in, say, Java. Depending on where they are placed, they mean different things. Example: this question.
I'm guessing the syntax error in the submitSearchForm function declaration is the source of your problem.
I'm still not sure that the code you've posted is actually the code the browser sees, but if so, try this:
function submitSearchForm(action, iskeyDown) {
var oneEntered = false;
if (iskeyDown === null || typeof iskeyDown === 'undefined') {
copyAndValidate("dobFrom", "searchCriteria.dob", "date");
copyAndValidate("dobTo", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
} else {
copyAndValidate("dobFrom_date", "searchCriteria.dob", "date");
copyAndValidate("dobTo_date", "searchCriteria.dobTo", "date");
copyAndValidate("dodFrom_date", "searchCriteria.dodFrom", "date");
copyAndValidate("dodTo_date", "searchCriteria.dodTo", "date");
copyAndValidate("searchCriteria.age", "searchCriteria.age", "integer");
}
var elements = document.SearchForm.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element !== null && element.getAttribute("group") === 'searchCriteria') {
if (!isEmpty(element.value)) {
oneEntered = true;
break;
}
}
}
if (oneEntered)
{
if (validate(document.SearchForm)) {
document.SearchForm.action.value = action;
document.SearchForm.submit();
}
}
else {
alert('<%= bpt.getValue("CCT_ATLEASTONE_MSG") %>');
}
}
window.event is IE's specific, take a look here for (a bit old) table for different browsers:
http://www.javascriptkit.com/domref/domevent.shtml
Here's the official documentation:
https://developer.mozilla.org/en/DOM/Event
Here's another post for that:
http://www.sitepoint.com/forums/showthread.php?t=330837
I had similar error just resolved the same.
The form tag should be under <html><body> tag. e.g. <html><body><form></form></body></html>
If you have just used <form></form> tag and trying to submit then it gives error in older version of mozill while it works in newer version and other browsers.

Categories

Resources