[英]How do I change the “checked” attribute of a check box when clicked?
我目前正在嘗試建立一個帶有復選框的列表,這些復選框可以輕松地選中/取消選中以包含或排除。 當頁面加載時,大多數列表項將具有復選框“ checked”屬性,以顯示該項被包括在內。 我試圖在用戶更改選擇時更改復選框屬性,以便我可以保存結果。
我已經嘗試了一些在Stackoverflow上找到的組合,但是都沒有更改屬性,我不確定我做錯了什么。
function check() { if ($("#working").prop("checked", true)) { $("#working").prop("checked", false) } else { $("#working").prop("checked", true) } } var data = { id: document.getElementById('workingId').value, visible: document.getElementById('working').checked }; $(document).on("click", ".save", function() { alert(data); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" id="workingId" value="13245"> <input type="checkbox" name="working" id="working" onclick="check(this);" checked> I am a check box <button type="button" class="btn save"> Save</button>
我希望打印一個數組,該數組具有復選框的ID(12345),以及該復選框是否現在處於選中狀態/未選中狀態。 任何幫助,將不勝感激。
不知道您的問題對不對。 這是你想要的嗎 ?
var data = {}; function check() { if ($("#working").prop("checked")) { data = { id: document.getElementById('workingId').value, visible: document.getElementById('working').checked }; } else { data = {}; } } $(document).on("click", ".save", function() { console.log(data); }); check();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" id="workingId" value="13245"> <input type="checkbox" name="working" id="working" onclick="check(this);" checked> I am a check box <button type="button" class="btn save"> Save</button>
這是通過多次檢查來實現的一種方法:
var data = {}; function check() { data = {}; $("[name=working]").each((ign, o)=>{ if ($(o).prop('checked')) data[o.id] = $(o).attr('data-val'); }); } $(document).on("click", ".save", function() { console.log(data); }); check();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" data-val="13245" name="working" id="working1" onclick="check(this);" checked> I am a check box <br> <input type="checkbox" data-val="23245" name="working" id="working2" onclick="check(this);" checked> I am other check box <br> <input type="checkbox" data-val="33245" name="working" id="working3" onclick="check(this);" checked> I am yet another check box <button type="button" class="btn save"> Save</button>
嘗試這個:
var $checkBox = $("#working");
var data = {
id: $("#workingId").val(),
visible: $checkBox.is(":checked")
};
$(".save").on("click", function () {
data.visible = $checkBox.is(":checked");
alert(JSON.stringify(data));
});
// Do other things with the 'data' object...
沒有onclick="check(this);"
需要邏輯。
筆記:
working
div,則將查詢選擇存儲在變量中。 在資源方面,DOM訪問/操作不像創建變量那樣便宜。 此外,您可以在checkbox
元素中使用HTML data-*
屬性來存儲“ workingId”並完全刪除hidden
元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.