Check checkbox input manually in click handler - javascript

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)">

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">

js checkbox NOT set a custom value if not checked

I am working on a form that someone else created that passes through information to Salesforce. But regardless of where it sends values to, the checkbox doesnt seem to behave as it should.
No matter checking or unchecking the checkbox, it will always output the 'xxx' value.
The javascript sets the value of another checkbox inside salesforce based on the first checkbox. If that checkbox is checked, set the 'optin' value to true, if not false.
I feel I need another line of code that says: if checkbox is checked then value=xxx. if not checked, nothing. Then based on that, the other if else can be run.
here is the html:
<input type="checkbox" value="xxx" id="industry_optin" name="industry_optin"> YES
This is the js: (it is part of a bigger part of js, so there is no close bracket)
$(document).ready(function() {
$('#industry_optin').on('change', function() {
if ($(this).prop('checked') === true) {
$('#optin').prop('checked', true);
} else {
$('#optin').prop('checked', false);
}
});
Your code has errors because of }); ending of code.
$(document).ready(function() {
$('#industry_optin').on('change', function() {
if ($(this).prop('checked') === true) {
$('#optin').prop('checked', true);
} else {
$('#optin').prop('checked', false);
}
});
});
Fiddle

Checking if input value isn't empty working as wanted

I have a few input fields that must be filled before some button becomes active. My code does this, but only works after filling all inputs fields I changed selection from last filled input field to any other. How to make it more dynamic and allow button to become active without changing selection?
$(function() {
$('body').on('change','#form2',function(){
if($("#name").val() != "" && $("#number").val() != "" && $("#shortname").val() != "")
{
$('#CreateConnections').removeAttr("disabled");
}
else
{
$('#CreateConnections').attr("disabled", true);
}
});
})
You can try binding both keyup and change to all input elements. Also:
instead of using != to evaluate the value, we can simply check the value itself: when not empty it will return true, without the need to make comparisons.
you should use .prop() when working with boolean attributes, like disabled, checked, readonly, selected and the likes, instead of .attr(). p/s: You should also avoid using .removeProp() or .removeAttr() whenever possible, as once removed they cannot be added back.
Here is the updated jQuery:
$(function() {
$('body').on('change keyup','#form2 :input', function() {
if($("#name").val() && $("#number").val() && $("#shortname").val()) {
$('#CreateConnections').prop("disabled", false);
} else {
$('#CreateConnections').prop("disabled", true);
}
});
});
Here is a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/7rK2p/

Javascript iterate through all checkboxes on submit, and set attribute if changed from original value

I am trying to make a javascript function similar to the following, except it will iterate through all the checkboxes when the user clicks the submit button:
$('.checkboxstatus').click(function(){
this.setAttribute('checked',this.checked);
if (this.checked && $(this).data("def") == 0){
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else if(!this.checked && $(this).data("def") == 'checked')
{
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else{
//no change in checkbox
this.setAttribute('changed', 'no');
}
});
When the user clicks submit, the function should be called and it should iterate through all checkboxes and see if the checkbox is checked and see if the data-def is checked or 0. If the checkbox is checked and data-def="checked" then nothing should happen. If the checkbox state is different from the data-def then an attribute ("changed") should be added to that checkbox with value of "yes". Any suggestions on how to go about this?
Your question almost gives you the answer. You need to attach a "submit" event handler to the form, then grab all input[type=checkbox] and set the "changed" attribute accordingly.
I'm not sure I get this, but the usual way to do something like this would be to set an initial state in data, then on submit, prevent the submit action, check all the checkboxes against that initial state data variable, and see if anything changed, if it did, trigger the native submit handler ?
var boxes = $('input[type="checkbox"]').each(function() {
$(this).data('initial_state', this.checked);
});
$('form').on('submit', function(e){
e.preventDefault();
var same_same = true;
boxes.each(function() {
if ( $(this).data('initial_state') !== this.checked ) { // has changed ?
$(this).data('changed', true);
same_same = false;
}
});
if ( ! same_same ) { // diffelent
this.submit();
} else {
alert('same same, but not diffelent!');
}
});

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