Alfred D'Souza
Alfred D'Souza
1 min read

Categories

Another magic trick that I love most is when objects disappear. Specially pretty ladies, I wonder what magicians do with them.

If magicians can make objects disappear, so can we. But we can only make elements disappear from our DOM using jQuery.

Check this post to see how this can be done using JavaScript

Let’s define our trick : We will remove textboxes from a div every time a button is clicked.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Remove textboxes</title>
		<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
	</head>
	<body>
		<h1>Remove Textboxes</h1>
		<div id="div-textbox-here">
			<input type="text" class="magic-text-box" />
			<input type="text" class="magic-text-box" />
			<input type="text" class="magic-text-box" />
			<input type="text" class="magic-text-box" />
		</div>

		<button id="btn-remove-textbox">Remove Textbox</button>
	</body>
  </html>

We have a div (div-textbox-here) with four textboxes. We also have a button (btn-remove-textbox). When a user clicks on this button we will remove the first textbox.

We use our .on() spell to listen when the button is clicked.

$('#btn-remove-textbox').on('click',function(event){

});

What do we do next, remove the first textbox from the div.

$('#btn-remove-textbox').on('click',function(event){
	$('#div-textbox-here').find('input').first().remove();
});

We have our button listening for a click. And as soon as it hears a click, it will

  • Go to the div (div-textbox-here)
  • find() all input elements
  • Get the first() input element
  • And remove() it

And like always we can extend this the way we want. Like we can make sure that there is always at least one element present in the div.

$('#btn-remove-textbox').on('click',function(event){
	if( $('#div-textbox-here').find('input').length > 1 ){
		$('#div-textbox-here').find('input').first().remove();
	}
});

This is what we do here

  • Go to the div (div-textbox-here)
  • find() all input elements
  • Check if number(length) of input elements is greater than 1
  • If yes then get the first() input element
  • And remove() it

Get full code on github.