Remove and add required validation dynamically

Hi,

I need to remove or add validation dynamically to select2 element. For example, when the page loads, I may want the element to be required, or may not. I can control that easy enough. But then, based on another click, I need to manipulate that ‘requirement’ using javascript. I’ve tried multiple things I’ve seen online, but haven’t gotten a solution.

One thing I found was that I could include the ‘required’ attribute in the select element. I did that and it works correctly giving me a message when I don’t select at least one element. But then, I tried this code to ‘remove’ required attribute:

$('#disciplinesCoveredID').removeAttr('required');

I’ve also tried this as well:

$('#disciplinesCoveredID').select2().removeAttr('required');

I’m sure it’s something simple I’m doing wrong. I need to be able to remove it and also add it back. Any suggestions?

Thanks!

Dave

The Select2 widget itself does not have a required configuration option. It is just a UI widget; the HTML <form> still acts on the underlying <select> element (whose value the Select2 widget modifies), so the HTML form validation should respect the presence or absence of the required attribute. In other words, your first code snippet should work (the second one won’t, because it’s trying to re-initialize the Select2 widget and then remove the required attribute).

I tried this on my Select2 test codepen page, using a checkbox with an onclick handler to toggle the required attribute on the <select> element, and it seems to work. The code to toggle the required attribute is: onclick="$('#my-select').attr('required', this.checked);". So you can just pass true or false as the second parameter of the .attr() method to set or unset the required attribute.