DIV CSS 佈局教程網

用 jQuery 依類型自動顯示與隱藏表單欄位
編輯:JavaScript綜合知識     

表單中常有「依選擇不同而顯示不同欄位」的需求,例如選了某個類型才顯示對應的設定。本文分享一段僅約 10 行的 jQuery 程式碼,就能讓表單根據單選按鈕的選擇,動態地顯示或隱藏欄位,並帶有滑動動畫,簡單又實用。

html

 

代碼如下:
<div class="control-group">
<label class="control-label">類型:</label>
<div class="controls control-row-auto" id="type">
</div>
<span class="auxiliary-text"></span>
</div>
<div class="control-group ctype ctype1 ctype2">
<label class="control-label">欄目模版:</label>
<div class="controls">
<select name="column_tpl" class="input">
</select>
</div>
<span class="auxiliary-text"></span>
</div>
<div class="control-group ctype ctype1">
<label class="control-label">文章模版:</label>
<div class="controls">
<select name="article_tpl" class="input">
</select>
</div>
<span class="auxiliary-text"></span>
</div>
<input type="hidden" name="tpl" id="tpl" value="" />
<div class="control-group ctype ctype3" style="display: none;">
<label class="control-label"><s>*</s>欄目鏈接:</label>
<div class="controls">
<input name="url" type="text" class="input-large" data-rules="{required:true,minlength:1,maxlength:30}">
</div>
<span class="auxiliary-text">內部鏈接格式:模塊/控制器/方法...,外部鏈接格式:https://../../</span>
</div>

 

js

 

代碼如下:
//根據類型自動顯示和隱藏表單
var input_type=$('input[name=type]');
function typeChangeHandle(){
var ctypes=$('.ctype');
var type=$(this).val();
var hideCtypes=ctypes.filter(':not(.ctype'+type+')').slideUp(500,function () {
$('.ctype'+type).slideDown(500);
});
}
typeChangeHandle.apply(input_type);
input_type.on('change',typeChangeHandle);
input_type=null;

 

這裡的關鍵,是用 filter(':not(...)') 選出「不需要顯示」的欄位先收起來,再把對應類型的欄位滑開,藉由 slideUp、slideDown 營造平順的切換過渡。

以上所述就是本文的全部內容了,希望大家能夠喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved