JackHasaKeyboard
JackHasaKeyboard

Reputation: 1665

if(element:contains) constantly returns true no matter what value or elements are involved

I'm attempting to hide a form's submit button until a certain kind of file has been selected using jQuery.

<input type="file" id="file">
<input type="submit" id="submit">

if($("#file:contains('.png')")) {
    alert("Yep, that's a PNG image");

    $('#submit').show();
}

jQuery constantly returns true no matter what value or elements are involved, as soon as the page loads the alert comes up and informs me that the file input contains ".png"

I understand this isn't really the right way to do this, by the way. I believe you can get around this by just using inspect element.

Upvotes: 0

Views: 44

Answers (2)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

DEMO

I hope you will be doing this in a change event of input file. So I suggest below work around to achieve this:

$('#file').change(function(e){
      var file = $(this).val();
      if(file!="" && file != null)
      {
          var ext = file.split('.').pop();//get the type
          if(ext=="png")
          {
               alert("Yep, that's a PNG image");
               $('#submit').show();
          }
          else
          {
               alert("Yawk!! Bad file");
               $('#submit').hide();
          }
      }
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Calling jQuery with a selector will always return a jQuery object which is always truthy that is why the if condition is return true always.

Also :contains checks for text content of the element, not value so you need to check whether the value of the file is having .png

$('#file').change(function() {
  var png = /\.png$/.test($('#file').val());
  if (png) {
    alert("Yep, that's a PNG image");
  }
  $('#submit').toggle(png);
})
#submit {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="file" id="file">
<input type="submit" id="submit">

Upvotes: 1

Related Questions