Matt
Matt

Reputation: 1257

Hide div based on dropdown selection

I have the following form:

<h5>Region</h5>
          <select class="form-control" name="region" id="region" >
                     <option value="">Select a Region</option>
                     <option value="US">US</option>
                     <option value="UK">UK</option>
                     <option value="XS">XS (Sales Team)</option>
                     <option value="XT">XT (Editorial Test)</option>
          </select>
      </div>
      <div class="col-md-3 portfolio-item">
      <h5>Duration</h5>
          <select class="form-control" name="duration" id="duration" >
                     <option value="">Select a Duration</option>
                     <option value="5">5 Minutes</option>
                     <option value="10">10 Minutes</option>
                     <option value="15">15 Minutes</option>
                     <option value="20">20 Minutes</option>
                     <option value="25">25 Minutes</option>
                     <option value="30">30 Minutes</option>
          </select>
      </div>

that when neither options is selected, this link needs to be hidden:

<a type="button" class="btn btn-default" id="link" value="JSON feed" target="_blank">Raw JSON</a>

I'm using the following jQuery to do so:

if($("#region").val() && $("#duration").val() === ''){
    $("#link").hide();
} 
else if{
    $("#region").val() && $("#duration").val() != ''){
    $("#link").show();
}

jsfiddle

Upvotes: 2

Views: 244

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241258

Listen to the change event of both select elements. Iterate through them to determine how many have selected values, and conditional show the link based on the count.

Updated Example

var $selectElements = $('#region, #duration');

$selectElements.change(function (e) {
    var selectedCount = $selectElements.filter(function() {
        if (this.value) { return this; }
    }).length;
    selectedCount > 1 ? $("#link").show() : $("#link").hide();
});

Upvotes: 1

Related Questions