簡體   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