0

I am using a jQuery script with PHP to conditionally show/hide form fields based on dropdown selection.
The script is:

//Hide the field initially
        $("#hide1").hide();

        //Show the text field only when the third option is chosen - this doesn't
        $('#project-type').change(function() {
                if ($("#project-type").val() == "Value 1") {
                        $("#hide1").show();
                }
                else {
                        $("#hide1").hide();
                }
        });

I want to be able to add an array of values to the if ($("#project-type").val() == "Value 1") so if there are five values, I want a certain field to show when values 1 and 3 are selected but not the others. I have tried a few methods but they all result in all the values showing the hidden field.
Any help is appreciated.

2 Answers 2

1

jQuery inArray should do the work;

var val = $("#project-type").val(); // Project type value.

var show = $.inArray(val, ['Value 1', 'Value 2', ...]) > -1 ? 'show' : 'hide'; // If the value is in the array, show value is 'show' otherwise it is 'hide'.

$("#hide1")[show](); // Show or hide $('#hide1').
Sign up to request clarification or add additional context in comments.

Comments

0

There are lots of options, an easy one would be to change your if to:

if ($("#project-type").val() == "Value 1" || $("#project-type").val() == "Value 3")

or:

if (["Value 1", "Value 3"].indexOf($("#project-type").val()) != -1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.