beginner
beginner

Reputation: 2508

How to delete a element which has focus

I want to delete a input which has focus , I don't want to give any ids initially to any input ,

$('button').on("click",function(){
$(':focus').remove();});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" /><br><br>
<input type="text" /><br><br>
<input type="text" /><br><br>
<button>Delete focused input </button>

When user selects any of these three input, and then if the user click delete button that selected input field should be deleted.

Thanks in advance!!!

Upvotes: 0

Views: 142

Answers (2)

Vinod Louis
Vinod Louis

Reputation: 4876

You need to save the last text box focus then use it to delete on button click like this The problem with your current implementation is you are removing the currently focus element which will obviously be button as focus happens prior click

var s = "";
$('input').on('focus',function(){
  s = this;
})
$('button').on("click",function(){
  $(s).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" /><br><br>
<input type="text" /><br><br>
<input type="text" /><br><br>
<button>
delete focused input </button>

Upvotes: 1

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You will need to store the element which had focus before button was clicked because when button will be clicked focus will shift to button.

<script>
  var element;
  $('button').on("click", function () {
    $(element).remove();
  });
  $("input").focus(function () {
    element = $(this);
  });
</script>

Upvotes: 1

Related Questions