I have a form with a file input and I want to check if it is empty when the form is submitted.
I have this code:
$('form#new_comment').submit(function(e) {
var $this = $(this);
var $input = $this.find('input').val();
if($($input == '')) {
alert ("you must choose a image");
return false;
e.preventDefault();
}
});
But it always says you must choose a image
, even when I have chosen an image.
Where is the problem?
To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.
jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.
You can use exclamation mark ! to check if it is null.
Change:
if($($input == '')) {
To:
if($input == '') {
Since it is simple variable that holds text, you don't need to use jQuery function over it again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With