Leandro Chaves Leandro Chaves - 25 days ago 11
PHP Question

Onchange with more than one select fields

I have a dashboard with data filled from the database.

First, I have a Select working as a filter like


"select X from Y where fieldX = (The key from select goes here)"


and then the data from dashboard changes.

Currently, I'm using the onchange property. Right after the select is fired the dashboard changes without a submit button.

But now, I want to put more Selects (like 4, like a form). The problem is that right after a select is fired the dashboard changes. Not a problem with just 1 select (expected effect), but I want to select more Selects fields to add more filters on my dashboard like


"select X from Y where fieldX = (The key from selectX goes here) and fieldZ = (The key from selectZ goes here) and [...]"


(note that the user chooses the filters. Some selects fields may be selected or not)

My question if there is a way, using onchange (or not), to do that. Maybe using a submit button or something?

Currently I'm using something like this:

//PEGANDO O SELECT REGIONAL PARA O GRÁFICO
$('select#SELECTID').on('change', function (e) {
var SELECTID = this.value;
//url
control('ocupantes-aptos/dashboard?SELECTID =' + SELECTID , 'content');
});

Answer

Same thing. You bind the event to all involved SELECTs. And if you have an ID (# selector) you need not specify SELECT. In the callback, you now have to explicitly retrieve each control's value:

$('#selectId1, #selectId2, #selectId3').on('change', function () {
  var s1 = $('#selectId1').val();
  var s2 = $('#selectId2').val();
  var s3 = $('#selectId3').val();
  //url 
  control('ocupantes-aptos/dashboard?SELECTID =' + s1 , 'content');
});

Or you can give a specific class to all those controls:

$('select.grupo1').on('change', ...

with

<select id="selectId1" class="grupo1">
    ...

Note: jQuery also has functions to efficiently serialize a form or a set of controls, so that you need not specify all those val()s.

Comments