nnachefski
nnachefski

Reputation: 1562

ajax, jquery, and filtering drop downs

So i have these two jquery functions which pass my XHR service a key to filter the results of my list (not shown). I'm new to jquery(and web dev in general). These two functions are %90 the same (except for the id tags). How could I re-write this to be more DRY-like?

  $('#id_group').change(function() {
    var option = $(this).val();
    $.get('jobs/update/', {group:option}, function(data) {
      $('#jobs').html(data).hide().fadeIn(1000);
    });
  });

  $('#id_location').change(function() {
    var option = $(this).val();
    $.get('jobs/update/', {location:option}, function(data) {
      $('#jobs').html(data).hide().fadeIn(1000);
    });
  });

Upvotes: 1

Views: 94

Answers (3)

Dormouse
Dormouse

Reputation: 5198

I'd use the same event handler for both and then just alter the backend slightly.

$(".get_selects").change(function () {
    var option = $(this).val();
    var type = $(this).attr("id");
    $.get('jobs/update/', {type: type, value: option}, function (data) {
        $('#jobs').html(data).hide().fadeIn(1000);
    });
});

I've changed the HTML a bit so check out the Fiddle: http://jsfiddle.net/uVahr/

Upvotes: 0

Hogan
Hogan

Reputation: 70513

By passing custom data to jQuery you can make use of the event object (documented here http://api.jquery.com/category/events/event-object/) and have one generic function to do both tasks.

 function doGet(e) {
    var option = $(e.target).val();
    $.get('jobs/update/',e.data, function(data) {
      $('#jobs').html(data).hide().fadeIn(1000);
    });

 $('#id_group').change( {group:option}, doGet);

 $('#id_location').change({location:option}, doGet);

Upvotes: 1

George Cummins
George Cummins

Reputation: 28906

If using classes is not an option, you can reference a defined function like this:

$('#id_group').change(function() {
    // Pass the element id to the defined function
    get_jobs( $( this ).attr( 'id' ) );
}
$('#id_location').change(function() {
    // Pass the element id to the defined function
    get_jobs( $( this ).attr( 'id' ) );
}

function get_jobs( id ) {
    var option = $( '#' + id ).val();
    $.get('jobs/update/', {location:option}, function(data) {
      $('#jobs').html(data).hide().fadeIn(1000);
    });
}

Upvotes: 1

Related Questions