How to check for empty value in Javascript? - javascript

I am working on a method of retrieving an array of hidden inputs in my form like so
<input type="hidden" value="12:34:00" name="timetemp0">
<input type="hidden" value="14:45:00" name="timetemp1">
<input type="hidden" value="15:12:00" name="timetemp2">
<input type="hidden" value="16:42:12" name="timetemp3">
<input type="hidden" value="16:54:56" name="timetemp4">
<input type="hidden" value="17:03:10" name="timetemp5">
My javascript function retrieves these individually by using getElementsByName('timetemp'+i)
for (i ; i < counter[0].value; i++)
{
//finds hidden element by using concatenation of base name plus counter
var timetemp = document.getElementsByName('timetemp'+i);
//if there is a value alert that value to user - this is just for testing purposes at the moment
//because there is only one of timetemp.i then it occupies position 0 in array
if (timetemp[0].value == null)
{
alert ('No value');
}
else
{
alert (timetemp[0].value);
}
}
So what should happen is it will alert the user of the value in that hidden input but if it comes accross an input with no value like this:
<input type="hidden" value="" name="timetemp16">
Then it will say "No value"
However th if function cannot seem to work with this:
I have tried:
(timetemp[0].value == null)
(timetemp[0].value === null)
(timetemp[0].value == undefined)
(timetemp[0].value == '')
It always seems to default to else clause.
Any ideas?

Comment as an answer:
if (timetime[0].value)
This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:
const isEmptyValue = (value) => {
if (value === '' || value === null || value === undefined) {
return true
} else {
return false
}
}

First, I would check what i gets initialized to, to see if the elements returned by getElementsByName are what you think they are. Maybe split the problem by trying it with a hard-coded name like timetemp0, without the concatenation. You can also run the code through a browser debugger (FireBug, Chrome Dev Tools, IE Dev Tools).
Also, for your if-condition, this should suffice:
if (!timetemp[0].value) {
// The value is empty.
}
else {
// The value is not empty.
}
The empty string in Javascript is a falsey value, so the logical negation of that will get you into the if-block.

Your script seems incorrect in several places.
Try this
var timetemp = document.getElementsByTagName('input');
for (var i = 0; i < timetemp.length; i++){
if (timetemp[i].value == ""){
alert ('No value');
}
else{
alert (timetemp[i].value);
}
}
Example: http://jsfiddle.net/jasongennaro/FSzT2/
Here's what I changed:
started by getting all the inputs via TagName. This makes an array
initialized i with a var and then looped through the timetemp array using the timetemp.length property.
used timetemp[i] to reference each input in the for statement

The counter in your for loop appears incorrect (or we're missing some code). Here's a working Fiddle.
This code:
//Where is counter[0] initialized?
for (i ; i < counter[0].value; i++)
Should be replaced with:
var timeTempCount = 5; //I'm not sure where you're getting this value so I set it.
for (var i = 0; i <= timeTempCount; i++)

const isEmptyValue = val => [null, undefined, ''].includes(val);

Related

Declaring a for loop function in javascript

I have a for loop that searches for a value in an array in my javascript code in couchDb. I want to make it into a function. This should be fairly simple but I am having trouble with it. This is the for loop(Which works perfectly fine):
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].address) return;
}
}
throw({forbidden: 'doc.address is required'});
And this is the way I wrapped it into a function:
function arrayReq(field, message) {
message = message || "Array must have a " + field;
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].field) return;
}
}
throw({forbidden: message});
}
I would think that the return in the function should stop the function from going any further but it still throws the error. Can someone tell me what I am doing wrong? Btw if i change field into address it works fine. Can I not make the address into a changeable variable?
I think the problem is that you are trying to use field as both a string variable, and a property of your object inside the destination[] array.
In your code, if the destination[i] object does not have a property called field (not the string value populated in the field parameter, but an actual property named "field") it will never evaluate to true and break out of the function.
To access a property of an object by using the string representation in javascript, you use the indexer syntax.
Try changing it from array.destination[i].field to array.destination[i][field]

JavaScript throws TypeError saying that my variable is undefined

I don't have much experience in JavaScript, so far I have this:
function loop() {
var authorDivs = document.getElementById('ctl00_MainContent_MCPObjectInfo_dvCreatorView').getElementsByTagName("div");
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (typeof divOfDiv.item(i) === 'undefined' || divOfDiv.item(i) === null) {
console.log("This is undefined or null");
}
else {
var realDivs = divOfDiv.item(i);
realDivs.item(i).textContent = "please work plz";
}
}
}
I get the following error from the console in FireFox: TypeError: realDivs is undefined on this line: realDivs.item(i).innerHTML = "please work plz";
Essentially what I have (in my mind) is a loop that goes through authorDivs and gets all of the divs within those divs and saves them in divOfDiv. I then check to see if the divs in divOfDiv are undefined or null, if they are not then those divs get saved in a variable realDivs which I then use to edit the innerHTML. That's what I'd ideally like to see happen, what is causing the error? What am I doing wrong?
Note: I do not have access to jQuery but only JavaScript.
Edit: I've added the changes suggested below and its fixed that -- thanks! But I'm now getting the following error: TypeError: realDivs.item is not a function
What is causing that? And on another note how do I know when I'm dealing with an array and when I'm dealing with an HTMLCollection? Do you just assume? I've never used a loosely typed language before so its new to me.
Well, you'll need to move that code inside the conditional block that is supposed to prevent it! Also, || "null" is not going to work as you expect, you'll need to check for || divOfDiv.item(i) === null explicitly.
So try
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (divOfDiv.item(i) == null) {
console.log("This is undefined or null");
} else {
var realDivs = divOfDiv.item(i)
realDivs.item(i).innerHTML = "please work plz";
console.log(divOfDiv.item(i));
}
}
However, that still doesn't really work for two reasons:
The i index you use to access the i-th divOfDiv comes from the iteration over authorDivs - hardly what you want. Instead, use a second loop over all divOfDivs.
Your realDivs variable does hold a single <div>, which does not have an .item method. You'd just directly access its .innerHTML property.
So you should use
var authorDivs = document.getElementById('authorView').getElementsByTagName("div");
for (var i=0; i<authorDivs.length; i++) {
var divsOfDiv = authorDivs.item(i).getElementsByTagName("div");
for (var j=0; j<divsOfDiv.length; j++) {
var realDiv = divsOfDiv.item(j);
realDiv.innerHTML = "please work plz";
console.log(realDiv);
}
}
it will happen in case when your if (typeof divOfDiv.item(i) === 'undefined' || 'null') returns true. Then you never initialize realDivs (what would happen if condition was falsy). Later you try to call item function on that unitialized object
There are two problems in the code.
comparing DOM object with 'undefined' and null. If div tag is not available in authorDivs[i], it will return empty DOM array. So, comparision of empty DOM array with undefined and null is not good approach. We can use array length property for doing validation.
divOfDiv = authorDivs[i].getElementsByTagName("div");
if(divOfDiv.length > 0) { console statement}
As item(i) is already return single DOM element, item(i) of "realDivs" variable is not proper approach. In addition to this, innerHTML method needs to be used after validating whether realDivs contains DOM element. Please update the code as below.
var realDivs = divOfDiv.item(i);
realDivs ? (realDivs.innerHTML = "please work plz"): null;
Note : item(i) will return null if DOM is not available.

javascript length of each file in an array

I have an array of files here and I want to check the length of each file.
If length is zero then return false.
function check()
{
var files = ["#File1","#File2","#File3"];
for (var i = 0; i < files.length; i++) {
if ($("#").find(files[i].val().length == 0)) {
return false
}
}
}
I am getting an exception "is not a valid function" here, can someone tell what is wrong in this statement which checks that each array element has some value.
if ($("#").find(files[i].val().length == 0))
Replace
if ($("#").find(files[i].val().length == 0)) {
By
if ($(files[i]).val().length == 0) {
Assuming (possibly incorrectly, since it's somewhat unclear) that the elements are actually <input type="file"> inputs and that it's the size of the selected files you want rather than the filenames, you can examine the files property of each element and get the size property of each element of that array:
$('#File1').on('change', function() {
alert(this.files[0].size);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="File1">
As far as I understand you want to check, if alle the files are given within input fields? Your check could look like this:
if ($(files[i]).val().length == 0)
I prepared a simple pen to show how the function check() could work on a button:
http://codepen.io/rias/pen/emjxJv
Also you could iterate through all of the input fields, if you give them a common class like .file-input and use jQuery to iterate over them:
function check () {
$('.file-input).each(function () {
if ($(this).val() == 0) {
return false;
}
});
return true; //return true, if everything is okay!
}

Jquery: create a javascript method called 'containsBlanks' that returns true if any inputs with class 'required' has an empty string in, false if not

I can't seem to quite figure this one out; not sure if I'm even providing a test
condition; Also, "blanks" variable is to hold the value of the elements with the".required" class during the loop.
function containsBlanks(){
var blanks = new Array();
$required.each(function(){
blanks.($(this).val() == "");
});
return(true);
}
Loop over your Nodes and check their value against ""..
function containsBlanks() {
var i, req = $('.required');
for (i = 0; i < req.length; ++i)
if (req[i].value === '')
return true;
return false;
}
If I understand you can do this like:
$('input.required').filter(function(){ return !this.value });
That will give you all required inputs that have an empty value (if any). Then you can check the length property to find out if there are any elements in that collection.

document.getElementsByName("cad.question7.answer8").disabled = 'false';

I want to enable the disabled text field based on selection of checkbox, so below is the JavaScript code to enable the text field based on selection of check box, which is not working for me and am using the struts 1.3 HTML tags
if(document.getElementsByName("cad.question7").checked = 'true'){
document.getElementsByName("cad.question7.answer8").disabled = 'false';
}
<html:checkbox value="Y" property="cad.question7" onclick="javascript:enableText7();" />
<bean:message key="cm.assessments.cad.question.7.a" />
<html:text size="10" disabled="true" property="cad.question7.answer8" tabindex="68" />
getElementsByName returns a HTMLCollection.
To access each element inside the collection either iterate through them or if you only have one, access the first one, similar to this:
document.getElementsByName("cad.question7.answer8")[0].disabled = false;
DEMO - Access first item in HTMLCollection
If you expect multiple matches iterate through them similar to this:
var index;
var elements = document.getElementsByName("cad.question7.answer8");
var count = elements.length;
for(index = 0; index < count; index++){
elements[index].disabled = false;
}
DEMO - Iterate through all items in the HTMLCollection
In addition when executing a conditional evaluation you use == or === as a single = will assign the right value to the left and not compare them with each other.
Your complete code may look similar to this, assuming only a single match is expected:
if(document.getElementsByName("cad.question7")[0].checked){
document.getElementsByName("cad.question7.answer8")[0].disabled = false;
}
DEMO - Example of new code above
In the if-condition, you want to use the == or === comparison operator, not the = assignment operator. But comparing against booleans is senseless, just use the boolean itself (or its negation).
document.getElementsByName returns not a single element, but a NodeList. You will need to iterate over it, or - for simplicity - access its first item.
Both the checked and disabled properties are boolean. You should not compare/assign string to them, but booleans.
if (document.getElementsByName("cad.question7")[0].checked) {
document.getElementsByName("cad.question7.answer8")[0].disabled = false;
}
You might even go with this:
var question = document.getElementsByName("cad.question7")[0],
answer = document.getElementsByName("cad.question7.answer8")[0];
answer.disabled = !question.checked;
It should be boolean. disabled takes boolean value and also getElementsByName return multiple elements in an array.
Issue with your disabled="false" is that it still leaves the attrbute disabled in your text input element.
Try this:-
if(document.getElementsByName("cad.question7")[0].checked){
document.getElementsByName("cad.question7.answer8")[0].disabled = false;
}
References:-
getElementsByName
disabled
Below JavaScript codes you can use, your wish.,
But i would suggest you to use this (First one):
if(document.getElementsByName("cad.question7").checked){
document.getElementsByName("cad.question7.answer8")[0].disabled = false;
}
or
if(document.getElementsByName("cad.question7").checked == true){
document.getElementsByName("cad.question7.answer8").disabled = false;
}
or
var chkTest = document.getElementsByName("cad.question7");
if(chkTest.checked){
document.getElementsByName("cad.question7.answer8").disabled = false;
}

Categories

Resources