Thursday, August 20, 2009

jQuery: To select elements from a iframe/frame

When we use jQuery selectors is necesary to deliver an argument of  document, ie, a HTMLDocument object. The problem is that don't work to use  .document or .contentDocument. To make work both,  IE and FF, we need to use  .contentWindow.document.

Ex: suppose a document with an iframe(id=frame_selector) inside it, and the document inside of the iframe have a form(id=sel_indice). We need to set a input element inside of the form with the count of the checked checkboxes before to run a submit of the form. We can use the follows code:

function doSubmit() {
var docSel=null;
$('#frame_selector').each( function(){ docSel=this.contentWindow.document;});
$("#sel_indice input[id='Cantidad']",docSel).val($("#sel_indice input[id*='check']",docSel).filter(":checked").length);

The important is the second code line. If you try to do a selector like  $("#sel_indice"), without the second argument, you will get a empty array as return of the jQuery selector, because jQuery uses the content of the DOM that include the iframe/frame definition as default  HTMLDocument, but not the DOM contained by the iframe/frame. Again, this works using Internet Explorer or FireFox.

No comments: