2016-02-18 30 views
-1

jQuery的 - 使文本字段時複選框被選中

$("#owncar").click(function() { 
 
    if ($(this).is(':checked')) { 
 
    $("#carnumber").attr('disabled', false); 
 
    } else { 
 
    $("#carnumber").val(''); 
 
    $("#carnumber").attr('disabled', true); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<tr> 
 
    <td>Have own car :</td> 
 
    <td> 
 
    <input type="checkbox" name="owncar" id="owncar" value="Y" /> 
 
    </td> 
 
</tr> 
 

 
<tr> 
 
    <td>Car Number :</td> 
 
    <td> 
 
    <input type="text" name="carnumber" id="carnumber" maxlength="10" disabled/> 
 
    </td> 
 
</tr>

當從用戶勾選複選框有自己的汽車,使汽車數量的文本字段,讓用戶在汽車數量填寫。

上面的代碼對我來說可以。
當點擊複選框時,還有其他方法可以啓用文本字段嗎?

回答

4

使用prop()設置複選框的checked狀態。要設置文本框的值,請使用帶回調的val()

// Use change event on the checkbox 
$("#owncar").change(function() { 
    // Cache checked status 
    var checked = this.checked; 

    // If checkbox is checked, enable the textfield 
    // else disable 
    $("#carnumber").prop('disabled', !checked).val(function(i, oldVal) { 
     // If the checkbox is not checked, then empty the value 
     return checked ? oldVal : ''; 
    }); 
}); 
-1

使用removeAttr方法

$("#owncar").click(function(){ 
    if($(this).is(':checked')){ 
     $("#carnumber").removeAttr('disabled'); 
    } else { 
     $("#carnumber").val(''); 
     $("#carnumber").attr('disabled', true); 
    } 
}); 
相關問題