So I have multiple forms on a page. Each form is identical except for the data they may contain. I am listening for changes to a specific elements that should modify other elements within its same form, but I am having trouble figuring out how to scope those actions within its own form. Here’s what I’ve got so far:
var ContactSponsor = new function(){
this.init = function(){
$('#SponsorStatus_ID').change(SponsorStatusChanged);
};
var SponsorStatusChanged = function(){
var $form = $(this).closest('form');
var selectedValue = $(this).find('option:selected').text();
if (selectedValue == 'Executed Contract') {
markFieldRequired('#NumVAPs', $form);
markFieldRequired('#SponsorWebsiteLevel_ID', $form);
autoFillFieldWithCurrentDate('#ContractDate', $form);
} else {
markFieldNotRequired('#NumVAPs', $form);
markFieldNotRequired('#SponsorWebsiteLevel_ID', $form);
}
};
var markFieldRequired = function(fieldID, $form){
$(fieldID, $form).siblings('label').addClass('required');
};
var markFieldNotRequired = function(fieldID, $form){
$(fieldID, $form).siblings('label').removeClass('required');
};
var autoFillFieldWithCurrentDate = function(fieldID, $form){
if ($(fieldID, $form).val() == '' || $(fieldID, $form).val() == '0000-00-00') {
$(fieldID, $form).val(getCurrentDate());
}
};
};
Also, I’m passing the form to each of the methods. Not sure if there is a way I can do this without passing it in every time.
It looks like you’re using duplicate IDs. That is probably going to cause problems. Rather than having each FORM include an input with
id=NumVAPs, remove the ID and then target the field by name instead e.g.$form.find('[name=NumVAPs]').And hey, while we’re at it, you might want to combine your
markFieldRequiredandmarkFieldNotRequiredfunctions into a singlesetFieldRequiredthat accepts a boolean indicating whether the field should be required or not.Also, if marking a field as required is purely cosmetic, you may want to consider handling that with some CSS instead. E.g.:
Then, add this CSS:
OR add that selector to the
.requiredblock. Also, you’ll have to add the classrequired-for-executedto each of the appropriate labels in the markup (i.e. don’t do it with javascript).