How to solve jQuery ids problem?

2

I have two forms almost identical, one for physical and another for legal entity and these forms are hidden and appear as the result of a jQuery().change that determines if it is the form for the individual or legal entity to be used.

In both forms I am calling ids identical where in pfisica has #estado and #cidade and pjuridica also, I need the same information.

A jQuery (). change function in select #estado calls the buscar_cidades() function that captures the selected state id and searches the database with Ajax.

As the 2 forms load on the same page and appear according to the choice between PF or PJ , how do I solve this problem of ids knowing that duplicate ids conflict in jQuery ?

One solution would be to create two pages but did not want to do that. Another solution would be to change the ids and duplicate the function get_cities and change the name of the function that would call the ids of the other form, but I think it's more POG than something else.

How to solve?

Website in question

    
asked by anonymous 21.10.2014 / 17:07

2 answers

2

If you have two selects on the same form my suggestion is:

$('#fpf select').on('change', buscar_cidades);

Within the function buscar_cidades() the this will point to the changed select. So you can get:

this.id // o id do select mudado
this.value // o valor selecionado no select que foi mudado
    
21.10.2014 / 20:08
3

Instead of identifying the fields by Id, assign a common class (same name) to both components, and select by the name of the class instead of selecting by Id.

For example:

$( ".cidade" ).change(function() {
  // ...
});
    
21.10.2014 / 17:12