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!
}
Related
I need to create a web page on which I have added a text field. I have set an ID to the text field (say, 'custom'). Now, I want to modify the webpage if the text field contains certain words.
For example, if the text field contains a word, say apple, I want to do something.
If the text field contains ball, I want to do something else.
And so on.
I had found this:
<script>
var check=document.getElementById("custom").value == "text_value";
//check will be true or false
if (check){ //do something if true}
if(!check){//do something if false}
</script>
I don't even know if it's correct or not, but, I realised, it won't be able to manage multiple conditions. Because, if the text contains apple, it won't contain ball, it will create wierd behaviour.
So, how can I achieve this?
Check out the following Vanilla JavaScript (plain JavaScript) example.
I.e. enter bla bla apple and you will get the expected result.
function doSomething() {
var text = document.getElementById("myInput").value;
if (text.includes("apple")) {
console.log("do something special because text contains apple");
}
else if (text.includes("ball")) {
console.log("do something special because text contains ball");
}
else {
console.log("text contains no special word");
}
}
Enter text: <input type="text" id="myInput" onkeyup="doSomething()">
Can you please run the code snippet below.
The trigger is onkeyup and was selected for demonstration purposes. You can change it as per your requirement, for example, run the javascript function watchWords upon pressing a button.
function watchWords()
{
var watch_words = ['apple', 'lemon', 'watermelon'];
var textvalue = document.getElementById('name').value;
for(var i=0; i<watch_words.length; i++) {
if (~textvalue.indexOf(watch_words[i])){
if(watch_words[i] == 'apple'){
console.log('Apple was found');
}
if(watch_words[i] == 'lemon'){
console.log('Lemon was found');
}
if(watch_words[i] == 'watermelon'){
console.log('Watermelon was found');
}
}
}
}
<input type="text" name="name" id="name" onkeyup="watchWords()" />
One option is to use an object indexed by the .values you want to identify, whose property values are the functions you you want to run for each, eg:
const objOfFns = {
apple() {
console.log('Apple!');
},
ball() {
console.log('Ball!');
bounceBall();
}
};
const { value } = document.getElementByid('custom');
const possibleFn = objOfFns[value];
// check hasOwnProperty to avoid accidentally referencing Object.prototype methods
if (possibleFn && objOfFns.hasOwnProperty(value) {
possibleFn();
}
Using jQuery on keyup event listener and includes function:
$("#custom").on("keyup", function() {
if (this.value.includes("apple")) {
// do something
}
});
The code above will check the custom input each time the user presses a key and execute the if block if the input string contains the word apple.
<script>
function common(arr1, arr2) {
var newArr = [];
newArr = arr1.filter(function(v){ return arr2.indexOf(v) >= 0;})
newArr.concat(arr2.filter(function(v){ return newArr.indexOf(v) >= 0;}));
return newArr;
}
var string = document.getElementById("custom").value;
var items = string.split(" ");
var yourlist = ["apple", "banana", "tomato"];
var intersection = common(yourlist, items);
for(i=0; i<intersection.length; i++){
console.log(intersection[i]);
var z = yourlist.indexOf(intersection[i]);
/* Your Logic Goes Here.. */
if(z == 0){
/* do something */
}else{
/* do something else */
}
}
</script>
Function Credits - https://gist.github.com/IAmAnubhavSaini
I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.
I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.
I have something like this
var Array = ["1","8","17","14","11","20","2","6"];
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8)
then change picture.src to srcpicture1
else
then change picture.src to srcpicture2
}
but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.
Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.
Thanks in advance.
What you can do is write yourself a function to check if an element belongs to an array:
function inArray(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
And the just do:
var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
// change picture.src to srcpicture1
} else {
// change picture.src to srcpicture2
}
It's a lot more readable to me.
For extra points you can add the function to the array prototype like so:
Array.prototype.has = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
};
And then the call would be
if (arr.has(8)) // ...
Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.
P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.
use this
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
ie version
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility
Why don't just you abort the loop when you find the right number :
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8) {
//change picture.src to srcpicture1
break;
}
}
You could sort the array first then check the array only up to the point at which a number would be in the array, were it to exist.
If you have unique keys and a faster retrieval is what you care about a lot, you can consider using a map instead of an array (if there's a hard-bound case of using an array, then it won't work of course). If using a map, you just check "if( num in arr ) ".
I have this jQuery code:
var $collapsibleProducts = $('.collapsible-body');
if ($collapsibleProducts.length != 0) {
$.each($('.collapsible-body'), function (i) {
if ($('.collapsible-body')[i].children.length === 0) {
$('.collapsible-body')[i].append("<span class='something'>something</span>")
}
});
}
But I only getting inside my div.collapsible-body this string "<span class='something'>something</span>" instead of html <span> tag with 'something' string.
Like this (image)
Is there something I doing wrong? or is there another way to do it?
No need to check for the length (jQuery's easy like that), and you're using the wrong kind of each. You're using the general iterator whereas jQuery has a special iterator for jQuery objects.
var $collapsibleProducts = $('.collapsible-body');
$collapsibleProducts.each(function(i, el) {
if ($(el).children().length === 0) {
$(el).append("<span class='something'>something</span>");
}
});
I have a javascript array that looks like this:
myFields = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-location","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
]
I'm able to loop through the array and deal with specific bits like this:
len = fields.length;
//first check to make sure required fields are filled in
for(i=0; i<len; i++) {
a = fields[i];
if(a[0] != "fb-method") {
// do stuff
}
}
I need to be able to (outside the loop) do something if a specific element isn't part of the array, specifically one that looks like this:
["fb-location","drop",false,""]
I've tried using jQuery's .inArray function, but it returns true even when it should return false. See fiddle here.
What's the best way to go about this? jQuery or standard js is fine.
$.inArray does not return a bool, it returns the index (if no match exists, it returns -1). You would want this statement (based on your jsfiddle):
if(jQuery.inArray("fb-location", tmp) > -1) {
alert("it exists");
}
else {
alert("it doesn't exist");
}
DEMO:
http://jsfiddle.net/azWLC/2/
UPDATE:
As mentioned in the comments, this is only a half solution since the array is multidimensional. I recommend first using $.map():
var tmp = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
];
var values = $.map(tmp, function(n, i){
return n[0];
});
if(jQuery.inArray("fb-location", values) > -1) {
alert("it exists");
}
else {
alert("it doesn't exist");
}
DEMO:
http://jsfiddle.net/azWLC/4/
jquery.inArray returns the index of the element. If it is not found it returns -1.. And any number except 0 is true and hence it says 'it exists'
Besides $.inArray you could use Array.filter on tmp this way:
if( tmp.filter(function(a) {return -~a.indexOf('fb-location');}).length ) {
// exists
}
JsFiddle
See also: Array.filter, Array.indexOf
Using JQuery, you'd use the JQuery grep method
if( $.grep(tmp,function(a) {return -~a.indexOf('fb-location');}).length ) {
// exists
}
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);