简体   繁体   English

使用jQuery禁用表单字段

[英]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. 当触发称为FST的某个事件时,我希望其他字段被禁用并自动用时间/数字填充。 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. 我设法解决了如何禁用事件字段的问题,但是无论我使用哪个select字段,它始终会自动填充数字,而且我无法想象为什么。 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 这是一个演示https://jsfiddle.net/02mv54ao/ ,尽管我只希望更改FST的时间,但它会在任何类型选择选项上更改

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);    
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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