JR Tan
JR Tan

Reputation: 1725

How to remove image input with required field by using javascript

I did a script that check the image width and remove the image if the width is lesser than certain amount.

The image field is required and after I removed it, it still passed the file validation.

sample: http://jsfiddle.net/AUQYv/3/

<form action="">
    <input type="file" id="file" required />
    <input type="submit" value="Submit">
</form>

Javascript

var _URL = window.URL || window.webkitURL;

$("#file").change(function (e) {
    var file, img;


    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            if(this.width<490||this.height<175){
            $("#file").val("").change();
            }
        };
        img.onerror = function () {
            alert("not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);


    }

});

Upvotes: 0

Views: 1001

Answers (2)

Netzach
Netzach

Reputation: 321

Try with this.

<form action="" id="form" method="post">
    <input type="file" id="file" required accept='image/png, image/gif, image/jpeg, image/jpg'/>
    //your button submit
    <a href="#" id="submitForm">Submit</a>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//When click the button
$('#submitForm').click(function(){
  var validation = true; //Var to validation true
  if($('#file').val()){ //There's image?
      if($('#file').width()<490 || $('#file').height()<175){
          validation = false;
      }
  }else{
     validation = false;
  }
  //Is true?
  if(validation){
    $('#form').submit();
  }else{
    alert("select a image");
  }
});
</script>

Upvotes: 0

steinmas
steinmas

Reputation: 398

Your conditional statement is setting file = this.files[0]. Change to ==

Edit: Since both commenters pointed out that I was wrong, replace $("#file").val("").change():

with

$("#file").replaceWith($("#file").clone());

Upvotes: 1

Related Questions