[英]How to Select an option on change event and trigger the other select option to respond?
[英]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()
change()
處理更改事件parent()
用於選擇元素的父級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.