Simon Holywell

Posts tagged jQuery

jQuery and iFrames

I worked on a project while ago that required the use of iFrames to create “AJAX” file uploads.  It took me a little while but I finally worked out how to get the contents of an iFrame using jQuery.  To get the contents of an iFrame we need to wait until the iFramed content has finished loading as well.

http://gist.github.com/294740

jQuery Using and Manipulating Select Lists

JQuery is a fantastic tool but sometimes its functionality can be obscure or doing it one way might not work in a certain browser (MSIE6 anybody!).  I have often found myself trying to remember the best way to work with HTML select lists so I am compiling this list of hints for future use and I hope that you find it useful.  All the examples below are written where this represents the select element of the select list.

First up getting the selected value from a select list is as simple as using the jQuery shortcut $(this).val();.  Simple isn’t it!  Setting the selected item is just as easy too…

jQuery has a nice shortcut for setting the selectedIndex/value of an HTML select list and its syntax is as so $(this).val('value');.

Finding an option in a select list by its value works out to be something like this $('option[value="value-to-search-for"]', this);.

Often I need to be able to reset the select list to its initial state when clearing/resetting a form for the next submission.  There is a jQuery shortcut for this which is $(this).val('');, but it does not work in IE for whatever reason so I devised $(this).val($('option:first', this).val());.  This basically sets the select lists value equal to the first option in the list.

The next item on the list is resetting the select list to a blank option, which is easy with the following syntax $(this).val(null);.

Now to add an option into a select list with jQuery $(this).append('<option value="Option Value">Option Name</option>'); and to remove an option from the list by value $('option[value="value-to-search-for"]', this).remove();.

The aforementioned tips and some extras are included in a syntax highlighted manner below for your perusal.

http://gist.github.com/294741