简体   繁体   中英

Disabling form fields on select using jQuery

I have a simple booking form with different types of events. When a certain event is triggered which is called FST I want the other fields to be disabled and autofilled with timings/numbers. I have managed to work out how to get the event fields to disable but no matter which select field I use it always autofills the numbers and I can't visualize why. Any help would be great.

<select id="jq-Type" name="Type">
  <option value="PET">Pre-Employment Training</option>
  <option value="FST">Functional Skills Testing</option>
  <option value="ICT">ICT Testing</option>
</select>

<script>
  $(document).on('change', '#jq-Type', function() {
    var shouldEnable = $(this).val() == 'FST';

    $("input[name='BookingLimit']:eq(0)").val('21');
    $('#jq-BookingLimit').prop('disabled', shouldEnable);
    $("select[name='StartTimeHour']:eq(0)").val('09');
    $('#jq-StartTimeHour').prop('disabled', shouldEnable);
    $("select[name='StartTimeMinute']:eq(0)").val('30');
    $('#jq-StartTimeMinute').prop('disabled', shouldEnable);
    $("select[name='EndTimeHour']:eq(0)").val('15');
    $('#jq-EndTimeHour').prop('disabled', shouldEnable);
    $("select[name='StartTimeMinute']:eq(0)").val('00');
    $('#jq-EndTimeMinute').prop('disabled', shouldEnable);
  });
</script>

Here's a demo https://jsfiddle.net/02mv54ao/ and even though I only want the timings to change for FST it changes on any of the Type select option

You are disabling the elements only if that value is selected, but you are always changing the other elements values no matter what.

Add "if" do your statement and you're good to go.

$(document).on('change', '#jq-Type', function() {
    var shouldEnable = $(this).val() == 'FST';
    if (shouldEnable){
        $("input[name='BookingLimit']:eq(0)").val('21');
        $("select[name='StartTimeHour']:eq(0)").val('09');
        $("select[name='StartTimeMinute']:eq(0)").val('30');
        $("select[name='EndTimeHour']:eq(0)").val('15');
        $("select[name='StartTimeMinute']:eq(0)").val('00');
    }
    $('#jq-BookingLimit').prop('disabled', shouldEnable);
    $('#jq-StartTimeHour').prop('disabled', shouldEnable);
    $('#jq-StartTimeMinute').prop('disabled', shouldEnable);
    $('#jq-EndTimeHour').prop('disabled', shouldEnable);
    $('#jq-EndTimeMinute').prop('disabled', shouldEnable);    
});

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