Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if input file filed is empty jquery

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?

like image 435
hyperrjas Avatar asked Feb 23 '12 10:02

hyperrjas


People also ask

How check input field is empty or not in jQuery?

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.

Is Empty jQuery?

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.

How can check hidden field value is null or not in jQuery?

You can use exclamation mark ! to check if it is null.


1 Answers

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.

like image 186
Sarfraz Avatar answered Sep 21 '22 04:09

Sarfraz