ibrewster
ibrewster

Reputation: 3612

HTML duplicate form without ID conflicts

I have a form set up that is displayed as a jquery UI dialog. Many of the elements have javascript associated with them that manipulate other objects on the form. So, for example, I might have something like the following:

$('#empNumber').change(function(){
    $.getJSON('getEmpInfo',{...},function(response){
        $('#empName').val(response.empName);
        ...
    }
})

Which would, of course, populate the employee name (and other info) when an employee number is entered.

I now want to display this same form in a second location on the page (visually it's a different tab than where the dialog is accessed from, but HTML wise it's simply a different div), as child of a different form rather than by itself.

My first thought, given that everything is template, was to simply include this form in the second location where I needed it. But now I have a problem: all the id's are duplicated. Which is not only bad practice, it breaks things like the code above.

So, basically, I need two copies of my form and associated javascript. One to display as a stand-alone dialog, and a second to display as a child of another object. I could, of course, change all the ID's, but then I'd have to have two copies of the code as well, which would be annoying at best. So what's the best solution?

Upvotes: 0

Views: 970

Answers (2)

Saransh Kataria
Saransh Kataria

Reputation: 1497

You could have them inside a div which has a unique id, and then using css selectors for descendants, select them uniquely.

Say I have

<div id="form1"> 
<input class = "empNumber" />
</div>
<div id="form2"> 
<input class = "empNumber" />
</div>

and then use $('#form1 .empNumber') to select the first one.

Upvotes: 2

Felipe Brahm
Felipe Brahm

Reputation: 3160

You just shouldn't use IDs if you're expecting to have more than one of them on the same page. Use classes instead:

$('.empNumber').change(function(){
    $.getJSON('getEmpInfo',{...},function(response){
        $('.empName').val(response.empName);
        ...
    }
})

Also, you'll need to modify your code so that all your selectors are self-contained and can't cause issues in other parts of the page. Usually I would do something like this:

var initializeForm = function($el) {
  // all selectors will be within the `.myFirstForm` or `.mySecondForm` wrappers
  $el.find('.empNumber').change(function(){
      $.getJSON('getEmpInfo',{...},function(response){
          $el.find('.empName').val(response.empName);
          ...
      }
  });
}

initializeForm($('#myFirstForm'));
initializeForm($('#mySecondForm'));

Upvotes: 3

Related Questions