jQuery if statement always evaluates to true - javascript

I am checking to see if a form has a "file" input and if it has a vlue. The DOM goes like:
<form id="form123">
<div class="row">
<input type="file">
</div>
</form>
Console
console.log($(formId).find('input[type = "file"]').val().length)
// prints 0
if statement
if ($(formId).find('input[type = "file"]').val().length > 0) {
// run function
It always runs the function!

.has() returns a jQuery collection, not a true/false boolean. So use:
if ($(formId).has('input[type="file"]').length)
.length returns the number of elements matched by .has().

I would use .find() as it has better performance.
if ($(formId).find('input[type="file"]').length > 0) {
}
Edit:
And since .length is an integer, I would compare it with another numeric value instead of just evaluate it to boolean like in other answers.
if (3 > 0) looks more reasonable than if (3), right?

the closing form tag is actually an open one, did you mean that? try removing the spaces between the attribute name and the value class='row'. You can also try $(formId).find(...)

Related

What does an if (number) return?

I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..
In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.
The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.
It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.
It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead
if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}
length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);

Javascript regex matching on a time

I want to see if the string I have is in the form of HH:MM:SS.
Here is what I have so far:
d = '00:01:01'
d.match(/\d{2}:\d{2}:\d{2}/)
["00:01:02"]
Is there a way to just get a True/False, instead of an array?
Use .test method of Regexp object.
/\d{2}:\d{2}:\d{2}/.test(d)
// true
Perhaps, you can use regex.test(str) but it's also possible using match because on success, match returns an array which is a truthy value and on failure, match returns null which is a falsy value. Check this to understand truthy and falsy.
So, if you use
if(d.match(/\d{2}:\d{2}:\d{2}/)) {
// true
}
else {
// false
}
This will work, check this fiddle as an example and this answer as well (about !!), I've used !! in my example, so you may have doubts.

Shorthand-if with character index check

I am using a shorthand if statement to check if content has an italic tag in it.
remove = (content.indexOf('<i>') === true) ? true : false;
alert("ORIGINAL CONTENT: " + content + "\nDoes content contain <i>? " + remove);
When that alert pops up, it shows the following:
Alert box shows < i > in string, but returns false
What am I doing wrong?
indexOf returns the position of the string inside another string, and -1 if it's not found. It's not like strpos in PHP. So you have to check content.indexOf('<i>') !== -1 instead.
In your case, I'd simply define
remove = content.indexOf('<i>') !== -1;
The ternary operator (I used to know that by this name) isn't really necessary here, as the comparison already gives the boolean value you need.
Mostly covered in other answers, but in:
> content.indexOf('<i>') === true
note that String.prototype.intexOf returns a Number and it is being compared to a Boolean. Since they are different Types, the result will always be false. If the equals operator "==" had been used, it would return true if the left hand expression returned any value other than zero (0).
Incidentally, italic text can be implemented using elements other than I, e.g. a span element with suitable styling applied through CSS.
Have you considered using Regex?
remove = /<i>/.test(content);
Thanks RobG for the correction.

How to know that a particular element is present or not?

How to know that a particular input type is present or not in a div?
If I use
$("#inputId").val()
And there is no element present on this, then js gives an error.
So how could I know that the input element named inputId is present or not?
Reply me ASAP
You could check if
$('#inputId').length > 0
i.e. if the current selector matched any elements.
But if $('#inputId').length == 0 then $('#inputId').val() will be undefined. This is different from the scenario where the input exists, because val() would always yield a string, that is or isn't null.
Now, you would produce an error only if you're trying to do stuff with the value, that may or may not be undefined. For instance, the following would not work if #inputId does not exist in the DOM:
if($('#inputId').val().length > 0) { ... }
... since you'd be trying to access undefined.length. However, you could still do
if(!!$('#inputId').val()) {
// this code will only be executed if #inputId exists, and has a value that
// is not an empty string
}
If you're writing form validation, it might be more useful to do
if($('#inputId').val() !== '') {
// this code will be executed if #inputId has a value, or if it does not
// exist in the DOM at all
}
The former condition checks that the result of .val() resolves to true, which is not the case for an empty string or for undefined. (It is also not the case for null, NaN, false or 0, but .val() will never yield any of those results)
The latter checks that the result of .val() is not exactly an empty string, which is true for an actual value, as well as for undefined.
You can use the length property, which will tell you the number of elements in the current selector.
if ($("#inputId").length > 0)
{
// code that depends on inputId being present can go in here
}
if ($("#inputId").length) { }
No need to be verbose, checking whether length === 0 or greater than 0: length value itself is automatically casted as a boolean inside an if statement
Without jQuery:
var input = document.getElementById('inputId');
if (input) {
// the input exists
alert(input.value);
} else {
// the input doesn't exist
alert('Ooops! An input with id "inputId" doesn\'t exist.');
}

Check for bool in JavaScript

I've got the following jQuery (I've got it wrapped in the document ready function and all that, so please know I'm just showing you the inside of the function.
..
var itemIsSold = $("#itemIsSold").val();
alert(itemIsSold);
if(!itemIsSold) {
...
}
where itemIsSold is a hidden input field. I get the value False upper case F when it hits the alert but never enters my next if statement. I know this has to be something stupid simple.
If the input's value contains the string "False", that will not translate into a false boolean value. You will need to actually check for itemIsSold == "False".
Since the value of the hidden input field is a string, !"False" will be evaluated to false. Note that any string other than a string with the length of 0 is treated as true. So you should rather compare the string value to another string value like "False":
if (itemIsSold == "False") {
// …
}

Categories

Resources