[英]get value of a checked bootstrap checkbox
我有這個 HTML 表單:
<div class="animated-switch">
<input id="switch-success" name="switch-success" checked="" type="checkbox">
<label for="switch-success" class="label-success"></label>
</div>
我怎么知道輸入是否被檢查?
我試過這樣但沒有任何提醒:
$(document).on('click','.animated-switch',function(e){
alert($('#switch-success:checked').val() );
});
這里有一個 JSFIDDLE 文件,以便查看我的清晰示例: https ://jsfiddle.net/s2f9q3fv/
如果選中該復選框,則會得到。
$('#' + id).is(":checked")
您的代碼在代碼段中運行良好。 您忘記為復選框添加值,但即使沒有它,您也應該能夠看到帶有未定義值的警報消息(請參閱下面的代碼段中添加了值“test”)。
$(document).on('click','#switch-success:checked',function(e){ alert($('#switch-success:checked').val() ); });
.animated-switch > input[type="checkbox"] { display: none; } .animated-switch > label { cursor: pointer; height: 0px; position: relative; width: 40px; } .animated-switch > label::before { background: black; box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.5); border-radius: 8px; content: ''; height: 16px; margin-top: -8px; position: absolute; opacity: 0.3; transition: all 0.4s ease-in-out; width: 40px; } .animated-switch > label::after { background: white; border-radius: 16px; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3); content: ''; height: 24px; left: -4px; margin-top: -8px; position: absolute; top: -4px; transition: all 0.3s ease-in-out; width: 24px; } .animated-switch > input[type="checkbox"]:checked + label::before { background: inherit; opacity: 0.5; } .animated-switch > input[type="checkbox"]:checked + label::after { background: inherit; left: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <div class="animated-switch"> <input id="switch-success" name="switch-success" checked="" value="test" type="checkbox"> <label for="switch-success" class="label-success"></label> </div>
更新:您應該在復選框本身而不是父級上綁定單擊事件。 用精美的動畫再次嘗試剪輯。 請注意,如果您希望始終執行警報,則必須刪除選擇器中的:checked
屬性。
試試這個
$(".animated-switch").change(function () {
alert($('#switch-success:checked').val() );
});
我仍然遇到問題並想出了一個解決方法:
<input class="form-check-input" type="checkbox" id="inlineCheckbox1"
onclick="document.getElementById('inlineCheckbox1').setAttribute('value',
document.getElementById('inlineCheckbox1').value * -1)" value='-1'>
<label class="form-check-label" for="inlineCheckbox1">1</label>
我設置了一個 'onclick' 事件,並將一個 'value' 屬性設置為 -1。 當您單擊復選框或標簽時,“值”將更改其符號。 因此,當您想要獲取值時,請獲取“值”屬性並檢查它是大於還是小於零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.