Reputation: 647
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!
Upvotes: 0
Views: 211
Reputation: 434
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(...)
Upvotes: -1
Reputation: 3614
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?
Upvotes: 0
Reputation: 782653
.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()
.
Upvotes: 3