Adding default option on the fly to select with jQuery, removing and some more…

The following snippet shows

  • How to add default option to select
  • How to manipulate elements that are created on the fly
	<head><title>Adding default selection list</title>
		<select name = "items" id="items">
			<option value="item1">Item One</option>
			<option value="item2">Item Two</option>
			<option value="item3">Item Three</option>
		<input type = "button" name="checkme" id = "checkme" value='check me' />
		<p class='static'>Existing Paragraph</p>
		<div class='newly'></div>
		<script type="text/javascript" src=""></script>
			$('#items').prepend('<option value= \'\' selected=\'selected\'>Select Item Please</option>');
				if ($('#items').val() != ""){
					$('<p>Yup you have selected ' + $('#items').val()+'<a href=\'\'>delete</a></p>').appendTo('.newly');
					alert('Plase select proper item');				
			$('p a').live('click',(function(){

				var remove = confirm("You sure to delete?");
				if (remove){
  			return false;


The prepend function on the selected element would put the given element on top of the list – there is also an append version of it
It would be difficult to access the elements that are created on the fly with jQuery without the use of live() – it binds the given click event to newly created elements.
Finally, when we delete, we want to delete the the paragraph as the whole that contains the anchor. Most of the time we want to do it with in the div tag.
In this case the anchor (a) is a child of the paragraph (p) – that is where the .parent().remove() would come to play.

, , , , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: