Если вы хотите, чтобы ссылка выдвигала флажок только в одну сторону, а не в другую (всегда делайте это истинным или всегда ложным), то вот решение:
// Get the link
var link = $('#edit');
// Get the checkbox
var checkbox = $('#myinput');
// Add an onclick to the link
link.on('click', function () {
// Get the value of the link attribute 'data-changecheckboxvalto'
var pushedValue = link.attr('data-changecheckboxvalto');
// Change the attribute checked accordingly
checkbox.prop('checked', pushedValue);
// NB : for jQuery < 1.6, use "checkbox.attr('checked', pushedValue);"
});
То же самое в чистом JS
// Get the link
var link = document.querySelector('#edit');
// Get the checkbox
var checkbox = document.querySelector('#myinput');
// Add an onclick to the link
link.onclick = function () {
// Get the value of changecheckboxvalto
var pushedValue = link.dataset.changecheckboxvalto;
// Change the value of the checkbox checked attribute
checkbox.checked = pushedValue;
};
Если, с другой стороны, вы пытаетесь сделать ссылку и флажок «близнецы», тогда вы можете избавиться от data-changecheckboxvalto
и выполнить одно из следующих действий:
Вот решение с использованием jQuery
// Get the link
var link = $('#edit');
// Get the checkbox
var checkbox = $('#myinput');
// Add an onclick to the link
link.on('click', function () {
// Get the value of the checkbox attribute 'checked'
var checkboxState = checkbox.prop('checked');
// NB : for jQuery < 1.6, use "checkbox.attr('checked');"
// Inverse the value of the attribute checked
checkbox.prop('checked', !checkboxState);
// NB : for jQuery < 1.6, use "checkbox.attr('checked', !checkboxState);"
});
То же самое в чистом JS
// Get the link
var link = document.querySelector('#edit');
// Get the checkbox
var checkbox = document.querySelector('#myinput');
// Add an onclick to the link
link.onclick = function () {
// Inverse the value of the attribute checked
checkbox.checked = !checkbox.checked;
}
Дайте мне знать:)