简体   繁体   English

Javascript根据选择其他字段禁用/启用输入字段

[英]Javascript disable/enable input field based on selection other field

I tried to follow answer here to do this in my code: How do I disable input field when certain select list value is picked but not working for me. 我尝试按照以下答案在代码中执行此操作: 选择某些选择列表值但对我不起作用时,如何禁用输入字段

I have an HTML select field id 'TfL' with Yes/No answer, and next field 'TfLroad' is an input field. 我有一个带有“是/否”答案的HTML选择字段ID“ TfL”,下一个字段“ TfLroad”是一个输入字段。 I want 'TfLroad' to load as disabled by default, then if 'TfL' changes from No to Yes, then 'TfLroad' should be enabled. 我希望默认情况下将“ TfLroad”加载为禁用状态,然后如果“ TfL”从“否”更改为“是”,则应启用“ TfLroad”。

Whole page code below, JS at top of file, these two fields next to bottom, tx any suggestions!: 下面是整个页面的代码,文件顶部是JS,底部是这两个字段,请发送任何建议!:

{% extends "base.jinja2" %}
{% block content %}

<script>

// value 0 for No answer to TfL road 1 for, in which case disabled, on change should
// enable TfLroad element by setting disabled = false, but not working yet!

document.getElementById("TfLroad").onload = function () {
    document.getElementById("TfLroad").disabled = true;
}

document.getElementById('TfL').onchange = function () {
    if(this.value = '0') {
        document.getElementById("TfLroad").disabled = true;
    }

    else {
        document.getElementById("TfLroad").disabled = false;
    }
}


</script>
                <h2 style="text-align:center">Add A 'Dummy' Street</h2>

<p>You can create a Dummy street here, which you will be able to search for in this application. This is to
demonstrate how a real Create &amp; Update Process could work for this application, without corrupting the original
data. Dummy streets are indicated in search results.</p>

<form class="form-horizontal" action = "" method="post">
  <fieldset>

     <div class="form-group">

        <div class="col-lg-6">
            <label for="stname" class="control-label">Street Name</label>
            <input class="form-control" id="stname" name="stname" pattern="^\S.{3,98}\S$"
                   title="Sorry, you must type from 5 to 100 characters, and no space at beginning or end."
                   placeholder="Full Street Name" required>
            <!--  required attribute needed because empty string bypasses the pattern regex. -->
            <span class="help-block">NB: No naughty word streets please, these will be deleted by admin!</span>
        </div>

<!-- CR, CL, PR, 25, 16, 19, BE, KN, SC, TH, WA, WH -->
        <div class="col-lg-3">
            <label for="distr" class="control-label">Postal District</label>
            <select class="form-control" id="distr" name="distr">
              <option>Croydon (CR0, CR2, CR7 or CR9)</option>
              <option>Coulsdon CR5</option>
              <option>Purley CR8</option>
              <option>London SE25</option>
              <option>London SW16</option>
              <option>Kenley CR8</option>
              <option>South Croydon CR2</option>
              <option>Thornton Heath CR7</option>
              <option>Warlingham CR6</option>
              <option>Whyteleafe CR3</option>
              <option>Beckenham BR3</option>
            </select>
            <span class="help-block">NB: Original data uses postal district only, hence problem with several postcodes for Croydon.</span>
        </div>

        <div class="col-lg-3">
            <label for="maint" class="control-label">Who looks after this street?</label>
            <select class="form-control" id="maint" name="maint">
              <option>Croydon Borough</option>
              <option>Transport for London</option>
              <option>Private Road</option>
            </select>
        </div>

    </div>

    <div class="form-group">
        <h4 class="centre">Street Number Limits for this Street Section<br/><small>Please leave as None if all properties in this section have names</small></h4>
    </div>

    <div class="form-group">
        <div class="col-lg-3">
            <label for="onb" class="control-label">Odd Numbers From</label>
            <input class="form-control" id="onb" name="onb" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
            <span class="help-block">e.g. '1' or '111'</span>
        </div>

        <div class="col-lg-3">
            <label for="one" class="control-label">Odd Numbers To</label>
            <input class="form-control" id="one" name="one" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
            <span class="help-block">e.g. '31' or '217'</span>
        </div>

        <div class="col-lg-3">
            <label for="enb" class="control-label">Even Numbers From</label>
            <input class="form-control" id="enb" name="enb" value="None" pattern="^\d*[02468]$|(None)" title="Even Numbers only please with no spaces, or None">
            <span class="help-block">e.g. '2' or '110'</span>
        </div>

        <div class="col-lg-3">
            <label for="ene" class="control-label">Even Numbers To</label>
            <input class="form-control" id="ene" name="ene" value="None" pattern="^\d*[02468]$|^(None)$" title="Even Numbers only please with no spaces, or None">
            <span class="help-block">e.g. '32' or '216'</span>
        </div>
    </div>

    <div class="form-group">
        <div class="col-lg-4">
            <label for="rdclass" class="control-label">Road Class</label>
            <select class="form-control" id="rdclass" name="rdclass">
              <option>Unclassified</option>
              <option>A Road</option>
              <option>B Road</option>
              <option>C Road</option>
            </select>
            <span class="help-block">Leave as Unclassified if in any doubt.</span>
        </div>

        <div class="col-lg-4">
            <label for="length" class="control-label">Length of this Street Section (whole no. metres)</label>
            <input class="form-control" id="length" name="length" value= 0 pattern="^[1-9][0-9]*$" title="Whole number of metres please, no spaces!" required>
        </div>

        <div class="col-lg-4">
            <!-- JS here to put in A B C / disable depending on what selected in rdclass box -->
            <label for="rdnum" class="control-label">Road Number</label>
            <input class="form-control" id="rdnum" name="rdnum" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number for the road class, no spaces!" value="None" required>
            <span class="help-block">Only for A/B/C roads e.g. 'A232', 'C3241'</span>
        </div>
    </div>

    <div class="form-group">
        <div class="col-lg-3">
            <label class="control-label left">Does one end of this street adjoin a TfL maintained street?</label>
            <select class="form-control" id="TfL">
              <option value="0">No</option>
              <option value="1">Yes</option>
            </select>
        </div>

        <div class="col-lg-4">
            <!-- JS not working yet to disable only if no selected in rdclass box -->
            <label class="control-label"><br/>&nbsp;Road Number of Adjoining TfL Road?</label>

            <input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$"
                   title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>

           <span class="help-block">E.g. 'A232', 'B2441'</span>
        </div>

    </div>

    <div class="form-group">
        <div class="centre">
            <button type="reset" class="btn btn-default">Reset Form</button>
            <button type="submit" class="btn btn-primary">Create Street</button>
        </div>
    </div>
  </fieldset>
</form>
{% endblock %}

Instead of setting disabled through javascript you could add the disabled to the HTML input element: 代替通过javascript设置禁用,您可以将禁用添加到HTML输入元素:

<input class="form-control" disabled="disabled" .... />

Then in your javascript: 然后在您的JavaScript中:

document.getElementById('TfL').onchange = function () 
{
    if (this.value == '0') 
    {
        document.getElementById("TfLroad").disabled = true;
    }

    else 
    {
        document.getElementById("TfLroad").disabled = false;
    }
}

disabled is a Boolean attribute. disabled是布尔值属性。 You don't disable an element by setting its attribute to disabled=false . 您不会通过将元素的属性设置为disabled=falsedisabled=false它。 The browser checks if your element HAS a disabled property and doesn't care if its disabled=true , disabled=false , disabled=elephant . 浏览器将检查您的元素是否具有disabled属性,并且不关心其元素的disabled=truedisabled=falsedisabled=elephant In order to "enable" your element you must completely remove the disabled attribute. 为了“启用”您的元素,您必须完全删除disabled属性。

This should work: 这应该工作:

document.getElementById('TfL').onchange = function () {
    if(this.value == '0') {
        document.getElementById("TfLroad").disabled = "elephant";
    }

    else {
        document.getElementById("TfLroad").removeAttr("disabled");
    }
}

Also when comparing two values use == and not = . 同样,在比较两个值时,请使用==而不是=

There are several problems in the HTML/script you provided. 您提供的HTML /脚本中存在几个问题。

  1. The <script> content is executing before the form fields exist ( onload code isn't implemented the way you've done it.) <script>内容在表单字段存在之前onload执行(未按您的方式实现onload代码。)
  2. You haven't picked a default value for TfL 您尚未选择TfL的默认值
  3. You haven't disabled TfLroad by default 默认情况下,您尚未禁用TfLroad
  4. You've got a typo in a comparison. 您在比较中有错别字。

Fixing in order: 固定顺序:

  1. move the <script> to the bottom of the page and remove the onload function. <script>移到页面底部并删除onload函数。
  2. assuming you want No selected by default: 假设您希望默认情况下No选择:

      <select class="form-control" id="TfL"> <option value="0" selected>No</option> <option value="1">Yes</option> </select> 
  3. Add disabled attribute 添加disabled属性

     <input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$" disabled title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required> 
  4. usie = instead of == (or === ): 用usie =代替== (或=== ):

     if(this.value = '0') { 

Should be 应该

    if(this.value === '0') {

(You could also rewrite the onchange handler): (您也可以重写onchange处理程序):

document.getElementById('TfL').onchange = function () {
  document.getElementById("TfLroad").disabled = (this.value === '0');
}

So the problem is load event does not work on all elements, it only supports the below HTML tags. 因此问题是load事件无法在所有元素上都起作用,它仅支持以下HTML标记。

<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">,
<link>, <script> and <style>

Refer here to know more. 请参阅此处了解更多信息。

Also I have changed the logic for applying the initial disabled condition, please check it! 另外,我已经更改了应用初始禁用条件的逻辑,请检查一下!

As an alternative you can watch for document.ready instead and then apply this change. 作为替代方案,您可以改为查看document.ready ,然后应用此更改。 Refer the below snippet. 请参考以下代码段。

 var select = document.getElementById('TfL'), input = document.getElementById("TfLroad"); document.addEventListener("DOMContentLoaded", function(event) { if (select.value === '0') { input.disabled = true; } else { input.disabled = false; } }); select.onchange = function() { if (this.value === '0') { input.disabled = true; } else { input.disabled = false; } } 
 <h2 style="text-align:center">Add A 'Dummy' Street</h2> <p>You can create a Dummy street here, which you will be able to search for in this application. This is to demonstrate how a real Create &amp; Update Process could work for this application, without corrupting the original data. Dummy streets are indicated in search results.</p> <form class="form-horizontal" action="" method="post"> <fieldset> <div class="form-group"> <div class="col-lg-6"> <label for="stname" class="control-label">Street Name</label> <input class="form-control" id="stname" name="stname" pattern="^\\S.{3,98}\\S$" title="Sorry, you must type from 5 to 100 characters, and no space at beginning or end." placeholder="Full Street Name" required> <!-- required attribute needed because empty string bypasses the pattern regex. --> <span class="help-block">NB: No naughty word streets please, these will be deleted by admin!</span> </div> <!-- CR, CL, PR, 25, 16, 19, BE, KN, SC, TH, WA, WH --> <div class="col-lg-3"> <label for="distr" class="control-label">Postal District</label> <select class="form-control" id="distr" name="distr"> <option>Croydon (CR0, CR2, CR7 or CR9)</option> <option>Coulsdon CR5</option> <option>Purley CR8</option> <option>London SE25</option> <option>London SW16</option> <option>Kenley CR8</option> <option>South Croydon CR2</option> <option>Thornton Heath CR7</option> <option>Warlingham CR6</option> <option>Whyteleafe CR3</option> <option>Beckenham BR3</option> </select> <span class="help-block">NB: Original data uses postal district only, hence problem with several postcodes for Croydon.</span> </div> <div class="col-lg-3"> <label for="maint" class="control-label">Who looks after this street?</label> <select class="form-control" id="maint" name="maint"> <option>Croydon Borough</option> <option>Transport for London</option> <option>Private Road</option> </select> </div> </div> <div class="form-group"> <h4 class="centre">Street Number Limits for this Street Section<br/><small>Please leave as None if all properties in this section have names</small></h4> </div> <div class="form-group"> <div class="col-lg-3"> <label for="onb" class="control-label">Odd Numbers From</label> <input class="form-control" id="onb" name="onb" value="None" pattern="^\\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None"> <span class="help-block">eg '1' or '111'</span> </div> <div class="col-lg-3"> <label for="one" class="control-label">Odd Numbers To</label> <input class="form-control" id="one" name="one" value="None" pattern="^\\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None"> <span class="help-block">eg '31' or '217'</span> </div> <div class="col-lg-3"> <label for="enb" class="control-label">Even Numbers From</label> <input class="form-control" id="enb" name="enb" value="None" pattern="^\\d*[02468]$|(None)" title="Even Numbers only please with no spaces, or None"> <span class="help-block">eg '2' or '110'</span> </div> <div class="col-lg-3"> <label for="ene" class="control-label">Even Numbers To</label> <input class="form-control" id="ene" name="ene" value="None" pattern="^\\d*[02468]$|^(None)$" title="Even Numbers only please with no spaces, or None"> <span class="help-block">eg '32' or '216'</span> </div> </div> <div class="form-group"> <div class="col-lg-4"> <label for="rdclass" class="control-label">Road Class</label> <select class="form-control" id="rdclass" name="rdclass"> <option>Unclassified</option> <option>A Road</option> <option>B Road</option> <option>C Road</option> </select> <span class="help-block">Leave as Unclassified if in any doubt.</span> </div> <div class="col-lg-4"> <label for="length" class="control-label">Length of this Street Section (whole no. metres)</label> <input class="form-control" id="length" name="length" value=0 pattern="^[1-9][0-9]*$" title="Whole number of metres please, no spaces!" required> </div> <div class="col-lg-4"> <!-- JS here to put in ABC / disable depending on what selected in rdclass box --> <label for="rdnum" class="control-label">Road Number</label> <input class="form-control" id="rdnum" name="rdnum" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number for the road class, no spaces!" value="None" required> <span class="help-block">Only for A/B/C roads eg 'A232', 'C3241'</span> </div> </div> <div class="form-group"> <div class="col-lg-3"> <label class="control-label left">Does one end of this street adjoin a TfL maintained street?</label> <select class="form-control" id="TfL"> <option value="0">No</option> <option value="1">Yes</option> </select> </div> <div class="col-lg-4"> <!-- JS not working yet to disable only if no selected in rdclass box --> <label class="control-label"><br/>&nbsp;Road Number of Adjoining TfL Road?</label> <input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required> <span class="help-block">Eg 'A232', 'B2441'</span> </div> </div> <div class="form-group"> <div class="centre"> <button type="reset" class="btn btn-default">Reset Form</button> <button type="submit" class="btn btn-primary">Create Street</button> </div> </div> </fieldset> </form> 

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

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