tags:

views:

33

answers:

3

I am making ajax call(ASP.NET 3.5) from dropdown change handler and trying to pass dropdown id into ajax call:

$('select.facility').change(function()
{
      if ($(this).val() != 0)
      {
            var params = new Object();
            params.facilityId = $(this).val();

            $.ajax(
                {
                    type: "POST",
                    data: $.toJSON(params),
                    dataType: "json",
                    contentType: "application/json",
                    url: "SomeURL.asmx/SomeMethod",
                    success: function(response)
                    {
                        //this is where I need to get a hold of my dropdown,
                        // $(this) obviously doesn't work, using just to illustrate  
                        $(this).closest('table').next('table')
                        .find('input.address').val(response.d.Address);

                    }  

      }
});

Is there any elegant way to do that?

A: 

If you don't insist on using AJAX you could simply set the AutoPostback property of your dropdown to true and handle the changed event in the code behind.

Darin Dimitrov
Thanks for reply. Actually I do insist on AJAX for multiple reasons.
Victor
+1  A: 
...
var parentContext = $(this);
$.ajax(
{
    type: "POST",
    data: $.toJSON(params),
    dataType: "json",
    contentType: "application/json",
    url: "SomeURL.asmx/SomeMethod",
    success: function(response)
    {
        //this is where I need to get a hold of my dropdown,
        // $(this) obviously doesn't work, using just to illustrate  
        parentContext.closest('table').next('table')
        .find('input.address').val(response.d.Address);

    }  
    ...
karim79
+2  A: 

You can use this, you just need to add the context option of $.ajax() so this is useful:

$('select.facility').change(function() {   
   if ($(this).val() == 0) return;
   var params = { facilityId = $(this).val() };
   $.ajax({
      context: this,                           //add this!
      type: "POST",
      data: $.toJSON(params),
      dataType: "json",
      contentType: "application/json",
      url: "SomeURL.asmx/SomeMethod",
      success: function(response) {
        $(this).closest('table').next('table')
               .find('input.address').val(response.d.Address);
      }  
   });
});
Nick Craver
thanks, this is most elegant way of doing itBtw looks like you wouldn't be able to use this `params` syntax if you had multiple parameters to pass
Victor
@Victor - You can, it would look like this: `var params = { name1: 'value1', name2: 'value2' }`, just use a comma between pairs :)
Nick Craver