简体   繁体   中英

show/hide div based on select value - jquery

I'm trying to check to see if the value of my dropdown is "Single Date" and then if so, to hide the div #ToDate. Not sure what I'm doing wrong here.

HTML

<div class="mc-form-field mc-full">
    <label for="formDate">Payment Date:</label>
    <select name="mc-formPaymentDate" id="PaymentDate">
        <option value="Please select">Please select</option>
        <option value="Single Date">Single Date</option>
        <option value="Date Range">Date Range</option>
        <option value="Single Month">Single Month</option>
        <option value="Last 30 Days">Last 30 Days</option>
        <option value="Last 60 Days">Last 60 Days</option>
        <option value="Last 90 Days">Last 90 Days</option>
    </select>
</div>

<div class="mc-form-field mc-half mc-inline">
    <label for="mc-formFromDate">From Date:</label>
    <input type="text" name="formFromDate" id="mc-formFromDate" class="mc-text">
</div>

<div class="mc-form-field mc-half mc-inline mc-right" id="ToDate">
    <label for="mc-formToDate">To Date:</label>
    <input type="text" name="formToDate" id="mc-formToDate" class="mc-text">
</div>

Javascript

$("#PaymentDate").change(function() {
    if (this.value == 'Single Date') {
        $('#ToDate').hide();
    }
}); 

Try this using jQuery toggle method which can take a boolean flag whether to show or hide the element.

$("#PaymentDate").change(function() {
   $('#ToDate').toggle(this.value != 'Single Date');
}); 

It works fine, but you need to explicitly show the ToDate again if the test is false:

$("#PaymentDate").change(function() {
    if (this.value == 'Single Date') {
        $('#ToDate').hide();
    } else {
        $('#ToDate').show();
    }
});

http://jsfiddle.net/mblase75/3F93A/

Did you try?

 <script type="text/javascript">
 $(document).ready(function(){
      $("#PaymentDate").change(function() { 
          if ($(this).val() == 'Single Date') 
               $('#ToDate').hide(); 
      }); 
 });
 </script>

Note that I use $(this).val() instead of this.value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM