I have one multi-select field whose values are coming from one table which has the following data.
Desc | Code
----------------
India | IN
Australia | AUS
Other | OTH
Requirement: In that multi-select field if Other
then a new field is getting populated as Please specify (Others)
in which we will add some text value.
-
If I am selecting
India, Other, Australia
then thePlease specify (others)
should be enabled and the text which the user has written should be retained in please specify others field. -
If I am selecting
India, Other
then removingOther
and again selectingother
then value ofPlease specify(others)
should be blank.
Problem: When I am selecting India, Other, Australia
then the Please specify (others)
field value is getting nullified.
My attempt:
function showHideOthers() {
var selectedValue = $("#field_id_ui").val();
if (null !== selectedValue) {
for (var i = 0; i < selectedValue.length; i++) {
if (selectedValue[i] == "OTH") {
$("#Others_section").show();
} else {
$("#Others_section").hide();
$("#Others_section").val("");
}
}
} else {
$("#Others_section").hide();
$("#Others_section").val("");
}
}
The fields for show and hide are taken from VTL file.
"#field_id_ui"
– This is storing all the selected value in the form of array. For e.g [AUS, IN, OTH]
2
Answers
The logic for hiding "other" depending on the contents of
$("#field_id_ui").val()
is slightly wrong. Here’s a simple approach you can try. See the docs for Array.includes.Your issue is with this code:
which runs on every loops. So if your selected values
["OTH", "IND"]
then the other input will be shown, then immediately hidden by the "IND" value.Add a
break
inside theif
and your code will work fine regardless of the order of select values.this assumes your HTML is built to match the provided javascript (which we’ve not seen).
Updated code
Snippet showing your code not working if
OTH
is not last valueSnippet showing your code working if
OTH
is the last value