How to resolve ids problem in jQuery?

Asked

Viewed 79 times

2

I have two almost equal forms, one for individuals and one for legal entities and these forms are hidden and appear as the result of a jQuery().change determining whether the form is for a natural person or a legal person to be used.

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

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

How the 2 Forms load on the same page and appear as you choose between PF or PJ, how I will solve this problem of ids knowing that duplicated ids conflict with jQuery?

A solution would be to create two pages but I didn’t want to do that. Another solution would be to change the ids and duplicate the function search_cities and change the name of the function that would call the ids of the other form but I think this more POG what else.

How to solve?

Website in question

  • 3

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

  • 1

    ^^^^this, the problem of Ids is solved with classes. [ps] if you publish a summary of your code here gives a more complete answer.

  • Thank you guys, as I finished the question, I thought class. I’m gonna test.

2 answers

3

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

For example:

$( ".cidade" ).change(function() {
  // ...
});

2


If you have two selects in 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.