萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 表單交互大全:按鈕、單選、複選、下拉、驗證

完整示範頁面

<!DOCTYPE html>
<html><head>
<script src="jquery-1.4.js"></script>
<script>
$(function() {
    // 按鈕點擊
    $('#but').click(function(){ alert('Hello'); });

    // 文本框取值
    $('#btext').click(function(){ alert($('#te').val()); });

    // 下拉框變化
    $('#sel').change(function(){ alert($(this).val()); });

    // 單選框取值
    $('input[name="radiobutton"]').click(function(){
        alert($('input[name="radiobutton"]:checked').val());
    });

    // 複選框取值(多值)
    $('#ucheck').click(function(){
        var vals = [];
        $('input[name="checkbox"]:checked').each(function(){ vals.push(this.value); });
        alert(vals.join(','));
    });

    // 全選/全不選/反選
    $('#checkall').click(function(){ $('input[name="items"]').prop('checked', true); });
    $('#checkallNo').click(function(){ $('input[name="items"]').prop('checked', false); });
    $('#check_revsern').click(function(){ $('input[name="items"]').each(function(){ this.checked = !this.checked; }); });
    $('#checkItems').click(function(){ $('input[name="items"]').prop('checked', this.checked); });

    // 表單驗證
    $('#nameid, #ageid').hide();
    $('#ubu').click(function(){
        if (!$('#name').val()) { $('#nameid').show().fadeOut(3000); return false; }
        if (!$('#age').val()) { $('#ageid').show().fadeOut(3000); return false; }
        alert('姓名:' + $('#name').val() + ' 年齡:' + $('#age').val());
    });
});
</script>
</head><body>
<input type="button" id="but" value="確認"><br>
<input type="text" id="te"><input type="button" id="btext" value="取值"><br>
<select id="sel"><option value="1">1</option><option value="2">2</option></select><br>
<input type="radio" name="radiobutton" id="uradio1" value="1">1
<input type="radio" name="radiobutton" id="uradio2" value="2">2
<input type="radio" name="radiobutton" id="uradio3" value="3">3<br>
<input type="checkbox" name="checkbox" value="A">A
<input type="checkbox" name="checkbox" value="B">B
<input type="checkbox" name="checkbox" value="C">C<br>
<button id="ucheck">取得複選值</button><br>
<input type="checkbox" name="items">1
<input type="checkbox" name="items">2
<input type="checkbox" name="items">3<br>
<button id="checkall">全選</button>
<button id="checkallNo">全不選</button>
<button id="check_revsern">反選</button>
<button id="checkItems">全選/反選</button><br>
<span id="nameid" style="color:red">請輸入姓名</span><br>
<span id="ageid" style="color:red">請輸入年齡</span><br>
<input type="text" id="name" placeholder="姓名">
<input type="text" id="age" placeholder="年齡">
<button id="ubu">提交驗證</button>
</body></html>

現代化改進建議

  • 用 .prop('checked') 替代 .attr('checked')(jQuery 1.6+)
  • 驗證用 required 屬性 + :invalid 偽類 + checkValidity()
  • 事件委託:$(document).on('click', 'selector', fn) 適用動態元素
  • 複選全選:$('#checkItems').change(function(){ $('input[name="items"]').prop('checked', this.checked); });
copyright © 萬盛學電腦網 all rights reserved