1

I'm loading HTML in dialog when button is clicked on

$("button").live('click', function() {
    var $div = $('<div title="Form"></div>');
    $div.load('test.html #formModal').dialog({
        width: 900,
        height: 500
    })
})

The HTML of #formModal looks like

  <form id="form">
    <input id="input1" type="button" />
    <input ...
  </form>
  <p id="formEdit"></p>

At this point HTML is successfully loaded in dialog

I also have the following, which when #input1 inside dialog is clicked, it will insert text inside #formEdit.

var $form = $('#form'); // global variable
var $formedit = $('#formEdit'); // global variable
$form.find('#input1').live('click', function(){
 $formedit.text('test'); //if i do $('#formEdit') instead of $formedit then it works
})

$formedit is not working here. It's not being passed to the click handler. it works fine if HTML was initially in body and not loaded in dialog using load(). What is causing this.

Pinkie
  • 10,126
  • 22
  • 78
  • 124
  • @mu `$('#formEdit')` works but not `$formedit`. This tell me that $formedit is being passed in. – Pinkie Apr 15 '11 at 02:30
  • @mu `$formedit` works if my HTML initially existed in DOM. But since i'm loading content inside dialog, it no longer works. I have to do `$('#formEdit')` for it to work. – Pinkie Apr 15 '11 at 02:34

2 Answers2

3

Since forModal is loaded dynamically formEdit is not avaialble with the regular page load.

Try this instead:

$("button").live('click', function() {
    var $div = $('<div title="Form"></div>');
    $div.load('test.html #formModal', function(){
      //#######ASSIGN THE #formEdit once the load is complete
      $formedit = $('#formEdit');
    }).dialog({
        width: 900,
        height: 500
    });

})
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • This is the way to do it. 'var' makes variable local to the context(function, document or window). – Daniel Protopopov Apr 15 '11 at 02:37
  • That worked. But now i have 2 references of the variables, inside load and outside. Removing either will break it again. Do we need to have the variables declared in both places. Does it make a difference if i have var infront of the variables – Pinkie Apr 15 '11 at 03:04
  • @Pinkie:You still have one variable. Only difference is you are reassigning a value to the variable $formEdit. Infact you can change the definition of the variable to var $formedit = null; from var $formedit = $('#formEdit'); – Chandu Apr 15 '11 at 03:07
  • I have been trying to resolve this problem for two days. It makes sense now. Thanks @Chandu. – Luis Carlos Chavarría Oct 25 '12 at 09:47
0

try something like:

var $form = $('#form'); // global variable
var $formedit = $('#formEdit'); // global variable
$form.find('#input1').live('click',{formedit: $formedit} , function(e){

 e.data.formedit.text('test'); //if i do $('#formEdit') instead of $formedit then it works
})
James Khoury
  • 21,330
  • 4
  • 34
  • 65