TheTallOne
TheTallOne

Reputation: 143

Third dropdown value dependant on first two dropdowns with jquery

I have the following code which changes the value of one dropdown (template) depending on the other (date):

<select name="date" id="date">
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>

<select name="time" id="time">
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>

<select name="template" id="template">
<option value="A">Template A</option>
<option value="B">Template B</option>
<option value="C">Template C</option>
</select>



    <script type="text/javascript">
    var templateA = ["11","12"]; //dates that use template A
var templateB = ["13","14"]; //dates that use template B
    jQuery('#date').change(function() {
      if (jQuery.inArray(jQuery(this).val(), templateA) != -1) {
        jQuery("#template").val("A");
      } else if (jQuery.inArray(jQuery(this).val(), templateB) != -1) {
        jQuery("#template").val("B");
      } 
    });
    </script>

I'm trying to include a third dropdown for 'time', so the template is dependant on date and time. For example, if date = 12 and time = pm, template = b, but if date = 12 and time = am, template = a.

There are plenty of posts on here about two dropdowns, but I couldn't find any for three.

The 'template' dropdown will be hidden and all three passed through in a wordpress contact form.

Upvotes: 0

Views: 292

Answers (1)

BeRecursive
BeRecursive

Reputation: 6376

Take a look at this jsFiddle. The long and short of it is you use a method to decide what template is chosen given the date and time values. You then just have two change listeners and call that method with the appropriate date and time in order to change the template value.

var templateA = ["11", "12"]; //dates that use template A
var templateB = ["13", "14"]; //dates that use template B

function calculateTemplate(date, time) {
    if (jQuery.inArray(date, templateA) != -1 && time === 'AM') {
        jQuery('#template').val('A');
    } else if (jQuery.inArray(date, templateA) != -1 && time === 'PM') {
        jQuery('#template').val('B');
    } else if (jQuery.inArray(date, templateB) != -1 && time === 'AM') {
        jQuery('#template').val('B');
    } else if (jQuery.inArray(date, templateB) != -1 && time === 'PM') {
        jQuery('#template').val('C');
    }
}

jQuery('#date').change(function () {
    calculateTemplate(jQuery(this).val(), jQuery('#time').val());
});

jQuery('#time').change(function () {
    calculateTemplate(jQuery('#date').val(), jQuery(this).val());
});

Obviously I've just made up your cases as an example.

Upvotes: 2

Related Questions