0
<input id="img" type="file" name="img" accept="image/*">

And this is the JQuery code:

$('#img').change(function(){

    if($('#this').val() === '') { 

        $("#subm").remove();

    }  else {

         $('<button id="subm" type="submit">Press</button>').insertAfter('#advice');

   }

});

I'm trying check if the input file is empty, if is empty, and exist a button called subm, I delete it, but if the input file has a file, I create that bottom. The problem is that, if there's a submbotton, because I select file, and after I change the input, let it empty, JQuery doesn't delete it.

How can I delete a button, created by JQuery, if an input file is empty?

Thank's advance!

1
  • 1
    You should always have a button. If the input is empty, you might disable or even hide it, but there is no reason to remove it. Commented Jan 21, 2013 at 14:05

4 Answers 4

3

$('#this') should be $(this), $('#this') matches an element with id=this

Sign up to request clarification or add additional context in comments.

Comments

3

Unless you actually have an element with an id of "this", you probably meant to use the this keyword instead:

$('#img').change(function(){
    // this will be the #img that fired the change event
    if($(this).val() === '') {
        $("#subm").remove();
    }  else {
         $('<button id="subm" type="submit">Press</button>').insertAfter('#advice');
    }
});

Comments

0

Use this:

<input id="img" type="file" name="img" accept="image/*">
<button id="subm" type="submit">Press</button>
$('#img').change(function(){
    if(!this.value) { 
        $("#subm").hide();
    } else {
        $("#subm").show();
    }
}).change(); // trigger event to init

Comments

0

One thing to note is that the value of this can also change depending on the context it is being used in with javascript and jQuery. You should be fine now, however in more complex situations, you could run into issues

The best practice for this situation is to create another variable, typically called self immediately.

$('#img').change(function () {
    var self = this;
    // self will now ALWAYS be the #img that fired the change event.
    if ($(self).val() === '') {
        $("#subm").hide();
    } else {
        $("#subm").show();
    }
});

The issue happens if you use another function lower down, then this would now refer to the this in the lower function. Define a new variable for self whenever you step inside a new function so that you will always lock into what this is. (And don't forget to have those variable names be unique.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.