Page 1 of 1

select2 conditional hide option

Posted: Tue Jul 16, 2024 7:57 pm
by Satrapo

Hi to all, I'm a beginner with select2!

I need to hide an option if MY_COND is true. (And show again when MY_COND is false)

I ended to use a listener to prevent selection this way:

$('#x_my_select').on('select2:select', function (e) {
	if ($(e.target).val() == "3" && MY_COND) { //3 IS THE VAL OF THE OPTION TO HIDE
		$(e.target).val(null).trigger("change") //RESET SELECTION
		ew.alert("OPTION NON ALLOWED!"); //NOT ALLOWED MESSAGE
	}
});

It works but I think that hide the option will be better, any suggestions are welcome!!

Thanks!


Re: select2 conditional hide option

Posted: Tue Jul 16, 2024 10:31 pm
by mobhar

You better use Lookup_Selecting server event in order to filter the option items that suits your needs.


Re: select2 conditional hide option

Posted: Wed Jul 17, 2024 12:51 am
by Satrapo

No, the problem is that MY_COND depends on user inputs in another fields of the add page

For EX:
input-text field: HOW LONG IS YOUR CAR IN CM

I catch the fields value with onchange linstener and set MY_COND to true or false.

And then only if the value is >450 MI_COND became true and I'have to hide ONE option in another select field of the add form.

(And show back if the user change the value to something < 450)

So if no one knows how to hide one options in select2 I'm going to disable select2 in advanced options
Thanks!!


Re: select2 conditional hide option

Posted: Wed Jul 17, 2024 9:43 am
by arbei

Note that the option to be hidden may be already loaded by Select2 or not, so your code should be able to handle both cases. If not loaded yet, you may search "addoption" in the forum. If already loaded, I don't think Select2 provides ways to hide an option, you may continue to use your existing code.