我有不同的形式,併爲每個字段集複選框字段集我有一個復位按鈕,但是當我點擊復位按鈕,每一個複選框復位..什麼javascript代碼我應該使用????復位元件
復位元件
回答
小提琴:http://jsfiddle.net/9MaLZ/10/
JS + JQ
// checking checkbox 1 for demonstration
$("#cb1").prop("checked", true);
// reset checkbox, closet to a reset button (up the dom)
$("#myform button").click(function(e) {
$(this).closest("fieldset").find(':checkbox').attr("checked", false);
});
// total reset
$("#totalrecall").click(function(e) {
$(":checkbox").each(function() {
$(this).attr("checked", false);
})
});
// check them all
$("#iwantthemall").click(function(e) {
$(":checkbox").each(function() {
$(this).attr("checked", true);
})
});
HTML
<div id="myform">
<fieldset>
<input type="checkbox" id="cb1" />
<button type="reset" id="cb1-reset">Reset</button>
</fieldset>
<fieldset>
<input type="checkbox" id="cb2" />
<button type="reset" id="cb2-reset" >Reset</button>
</fieldset>
<fieldset>
<input type="checkbox" id="cb2" />
<button type="reset" id="cb3-reset">Reset</button>
</fieldset>
<button type="reset" id="totalrecall">RESET ALL</button>
<button type="reset" id="iwantthemall">RESET ALL</button>
</div>
在普通的JavaScript,你可以使用像下面這樣。它重置在一個字段爲其默認所有的複選框選中狀態,無論是被選中或取消選中:
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
do {
el = el.parentNode;
if (el.tagName.toLowerCase() == tagName) {
return el;
}
} while (el.parentNode)
}
function resetField(el) {
var fieldset = upTo(el, 'fieldset');
var input, inputs;
if (fieldset) {
inputs = fieldset.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
if (input.type == 'checkbox') input.checked = input.defaultChecked;
}
}
}
</script>
<form>
<fieldset>
<input type="checkbox" name="cb0" checked>
<input type="checkbox" name="cb1">
<input type="button" onclick="resetField(this);" value="Reset field">
</fieldset>
<fieldset>
<input type="checkbox" name="cb2">
<input type="checkbox" name="cb3" checked>
<input type="button" onclick="resetField(this);" value="Reset field">
</fieldset>
</form>
我認爲一個jQuery oneliner就是這樣做的:'$(this).closest(「fieldset」)。find(':checkbox' ).attr(「checked」,false);':) –
@ Jens-AndréKoch-所以你加載了4000行代碼,並且仍然不能像復位按鈕那樣工作。 – RobG
克服它。 20行jQuery。測試小提琴:http://jsfiddle.net/9MaLZ/10/ –
- 1. 復位數組元素
- 2. 重複元件
- 3. 複製元件
- 4. 相對位元件
- 5. 位元件向右
- 6. 手動復位事件,自動復位事件
- 7. 移位和複製std ::向量元素
- 8. 定位一個重複元素--CSS
- 9. 修復元素滾動時的位置
- 10. 複雜的定位元素(乘行)
- 11. Preact-compat的復位元件<undefined></undefined>
- 12. 復位條件熊貓
- 13. 文件上傳復位
- 14. .NET手動復位事件
- 15. 組件當值復位
- 16. 形式onreset事件復位
- 17. 定位元件陣列
- 18. 定位元件下另一
- 19. 拴系元件位置
- 20. 位元件在網頁中
- 21. 元件位置顯示
- 22. 移位和合並元件
- 23. 將追加元素的位置恢復到以前的位置
- 24. 的Excel/Excel VBA中剪切和複製復位單元名稱
- 25. ListView元素的子元素在某個位置後重復
- 26. 角NG-重複,元件
- 27. 如何在靜態定位元件前面堆疊固定定位元件?
- 28. 複選框計數器因條件邏輯插件而復位
- 29. 的Javascript按位復位值
- 30. 重複文件指向同一位置
請出示您的(相關)HTML。 –
您可以在字段集中找到所有複選框,並設置'button.checked = button.defaultChecked;'將其返回到默認的「chechedness」(可能未檢查,但這將允許一些默認選中)。 – RobG
有沒有jQuery? –