Backbone - Checkbox stays checked? - javascript

I'm trying to hook up a checkbox to my View, but as soon as I tick it, it stays checked, even when I click it again?
Here's part of the View:
views.PaginatedView = Backbone.View.extend({
events: {
'click input.completedEnquiries': 'filterCompletedEnquiries'
},
filterCompletedEnquiries: function (e) {
return e.currentTarget.checked;
}
});
Heres the template:
<label>Show Completed: <input type="checkbox" class="completedEnquiries" /></label>
I've no idea what I'm doing wrong here?
Edit
Here is a Jsfiddle of the problem: http://jsfiddle.net/9cvVv/167/

The problem is returning e.currentTarget.checked from your event handler. Returning true or false from this handler will check or uncheck the box for you
filterCompletedEnquiries: function(e) {
//return e.currentTarget.checked;
},
comment out that return statement, and it works fine. You can still grab the info, but don't return anything from the method.
filterCompletedEnquiries: function(e) {
var isChecked = e.currentTarget.checked;
// do stuff here, based on it being checked or not
},
Edit
Here's an example, based on the conversation in the comments:
views.PaginatedView = Backbone.View.extend({
events: {
'click input.completedEnquiries': 'completedEnquiriesClicked'
},
// this is explicitly an event handler, and that's all it should be used for
completedEnquiriesClicked: function(e){
this.showCompletedEnquiries = e.currentTarget.checked;
},
doSomething Else: function (e) {
// now that we need to know, we can just check that attribute
if (this.showCompletedEnquiries){
// do something here
}
}
});
This is just one of many options you have, for making this work the way you want.

Related

Run code that decides if checkbox/radio will be checked before actually checking anything (javascript)

I'm building a cart app in Javascript and jQuery that needs to run some logic whenever a product is clicked. The clicked elements are radio buttons and checkboxes and the code will check if the right conditions are met for adding the product to the cart.
My initial way of trying to do this was to run preventDefault() at the start of my function, run some logic that decides if it's ok to add the item, and if so, add it to the cart and check the input element.
Looks sort of like this:
$(document).on("click","[data-item]", function(event) {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
if (event) {
event.preventDefault();
}
// pseudo code...
if (conditionIsMet === true) {
cart.addItem(target);
}
}
cart.addItem = function(item) {
products.push(item);
var element = $('[value=' + item.key + ']');
element.prop('checked', true);
};
My problem is that it seems that I can't use element.prop('checked', true); in my addItem function, since preventDefault stops that.
Can I get around this someway or what route should I go to get my wanted functionality? I really wan't to stop the form elements from getting checked at all and only check or uncheck through my app instead.
It seems that it's not possible to set the checked property of a checkbox right after preventDefault was called on it. Try wrapping your prop call with setTimeout, which will make sure that the update of the checked property occurs in another turn of the event loop:
$("#cb").on("click", function(event) {
updateCart(this, event);
});
const updateCart = function(target, event) {
if (event) {
event.preventDefault();
}
// pseudo code...
if (true === true) {
addItem(target);
}
}
const addItem = function(item) {
setTimeout(function() {
$('#cb').prop('checked', true);
})
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb">

Check checkbox input manually in click handler

So I have this code snippet that handles click events on input[type=checkbox]. What I want to achieve is to set checked property manually, depending on the if condition scope.vm.checkedRows.indexOf(orderId) === -1 (here the false/true assignment is inverted to make the point), however it does not work.
link: function(scope, element) {
element.on('click', '.csv-ignore input', function(event) {
scope.$apply(function() {
var orderId = angular.element(event.target).closest('tr').data('order-id')
if (scope.vm.checkedRows.indexOf(orderId) === -1) {
scope.vm.checkedRows.push(orderId);
event.target.checked = false;
} else {
scope.vm.checkedRows.splice(scope.vm.checkedRows.indexOf(orderId), 1);
event.target.checked = true;
}
});
return false;
})
}
Checkbox does not get checked/unchecked. What I found interesting is that then I comment out return false it works fine. However I initially added return false to prevent default behavior and check/uncheck checkbox manually. Do you know what is wrong with this code?
Maybe you can directly put an expression in ng-checked and do rest of the operation in the controller's on click. It will set checked value dynamically
<input type="checkbox" ng-model="item" ng-checked="(vm.checkedRows.indexOf(orderId) !== -1)">

Avoid clicking twice to begin editing boolean (checkbox) cell in Backgrid

We are using Backgrid and have discovered that to begin editing a "boolean" (checkbox) cell in Backgrid, you must click twice: the first click is ignored and does not toggle the state of the checkbox. Ideally we would get to the root of what is causing this behavior (e.g. is preventDefault being called) and solve it there, but I at first I tried a different approach with the following extension of BooleanCell's enterEditMode method which seemed like a logical place since it was upon entering edit mode that the checkbox click was being ignored.
Problem is my attempt also toggles the state of the previously edited checkbox. Here is the code.
var BooleanCell = Backgrid.BooleanCell.extend({
/*
* see https://github.com/wyuenho/backgrid/issues/557
*/
enterEditMode: function () {
Backgrid.BooleanCell.prototype.enterEditMode.apply(this, arguments);
var checkbox = this.$('input');
checkbox.prop('checked', !checkbox.prop('checked'));
}
});
The following seems to work:
var BooleanCell = Backgrid.BooleanCell.extend({
editor: Backgrid.BooleanCellEditor.extend({
render: function () {
var model = this.model;
var columnName = this.column.get("name");
var val = this.formatter.fromRaw(model.get(columnName), model);
/*
* Toggle checked property since a click is what triggered enterEditMode
*/
this.$el.prop("checked", !val);
model.set(columnName, !val);
return this;
}
})
});
This is because the render method gets called by Backgrid.BooleanCell's enterEditMode method on click, and said method destroys and re-creates the checkbox as follows but in so doing loses the checked state (after the click) of the original "non-edit-mode" checkbox
this.$el.empty();
this.$el.append(this.currentEditor.$el);
this.currentEditor.render();
A simpler approach:
var OneClickBooleanCell = Backgrid.BooleanCell.extend({
events: {
'change input': function(e) {
this.model.set(this.column.get('name'), e.target.checked);
},
},
});
This bypasses the CellEditor mechanism entirely and just reacts to the input event on the checkbox by updating the model.

How to get the current active element in chrome?

I am trying to use a if statement to determine which button/textbox is submitted.
For example In firefox/IE/Opera, the following code can always return true when I click the button labeled submitNameSearch as id;
$(document.activeElement)[0] === $("#submitNameSearch")[0]
However, when I test my code in chrome/safari, the return value is false.
May I ask if I did anything wrong?
Thanks a lot for your help!
If it's triggered on a click, why don't you just do:
$('button').on('click', function() {
if (this.id=='submitNameSearch') {
//do something
}
});
and to see what element had focus before the focus was shifted to the clicked button you can always do :
var activeElm = null;
$('button').on({
mousedown: function() {
activeElm = document.activeElement;
},
click: function() {
if (activeElm&&aciveElm.id=='submitNameSearch') {
activeElm.focus; //returns focus
}
}
});

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
The click() method
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.
Setting checked to a specific value
You could test the checked attribute, before calling the click() method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Using vanilla js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
For single check try
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
If, for some reason, you don't want to (or can't) run a .click() on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()

Categories

Resources