繁体   English   中英

在选择输入中的选择选项上触发事件

[英]Trigger event on select option in select input

我在选择输入上触发事件时遇到问题。 选择“另一个”选项时,我需要显示输入类型文本。 这是代码:

HTML:

<div class="form-group">
    <label class="control-label" for="affiliation">Occupation:</label>
    <select name="affiliation" id="affiliation" class="form-control required>
        <option value="Choose" selected>Choose</option>
        <option value="valueA">Student</option>
        <option value="valueB">Lecturer</option>
        <option value="valueC">Scientist</option>
        <option value="Another">Another</option>
     </select>
</div>
<div class="form-group hide">
     <input type="text" name="anotherV" id="anotherV" class="form-control" placeholder="Plese enter your occupation" required>
</div>

CSS:

.hide {display: none;}

我使用引导程序

在您的选择中的form-control之后,您的 HTML 中缺少结束双引号。 下面是固定的,并且在隐藏输入字段的父 div 中添加了一个 ID,以使代码更容易理解,如果您觉得舒服,可以随意更改。

HTML

<div class="form-group">
    <label class="control-label" for="affiliation">Occupation:</label>
    <select name="affiliation" id="affiliation" class="form-control" required>
        <option value="Choose" selected>Choose</option>
        <option value="valueA">Student</option>
        <option value="valueB">Lecturer</option>
        <option value="valueC">Scientist</option>
        <option value="Another">Another</option>
     </select>
</div>
<div class="form-group hide" id="hiddenInputContainer">
     <input type="text" name="anotherV" id="anotherV" class="form-control" placeholder="Plese enter your occupation" required>
</div>

jQuery

 $( "#affiliation" ).change(function(event) {
        if ($(this).val() === "Another") {
            $('#hiddenInputContainer').toggleClass('hide');
        }
  });
$("#affiliation").change(function() {
   if (this.value === "Another") $(".hide input").show()
   else $(".hide input").hide()
})

您可以将change()事件处理程序与toggleClass()

  1. 使用change()处理更改事件
  2. parent()用于选择元素的父级
  3. toggleClass()带有用于切换类hide标志

演示:

 $('#affiliation').change(function() { $('#anotherV').parent().toggleClass('hide', this.value != 'Another'); });
 .hide { display: none; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="form-group"> <label class="control-label" for="affiliation">Occupation:</label> <select name="affiliation" id="affiliation" class="form-control required"> <option value="Choose" selected>Choose</option> <option value="valueA">Student</option> <option value="valueB">Lecturer</option> <option value="valueC">Scientist</option> <option value="Another">Another</option> </select> </div> <div class="form-group hide"> <input type="text" name="anotherV" id="anotherV" class="form-control" placeholder="Plese enter your occupation" required> </div>

暂无
暂无

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

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