Checkbox ambiguous behaviour - javascript

Application includes Jquery 1.9.1, undescore.js and jquery plagin dataTables.
My checkboxes are wrapped as follows:
<label style="top: 3px; position: relative;" class="checkbox" id="IsSpreadCheckBox">
<input type="checkbox" name="IsSpread" id="IsSpread">
<span></span>
</label>
Element label.checkbox span has background images for each case: checked, unchecked, disabled.
Jquery onclick handler for it:
$(".checkbox span").click(function () {
var backgroundContainer = $(this); //span with background image
var checkbox = backgroundContainer.parent().find("input[type='checkbox']"); //hidden checkbox itself
if (!backgroundContainer.hasClass("disabled")) {
if (backgroundContainer.hasClass("checked")) {
checkbox.removeAttr('checked').prop("checked", false);
//Also tried checkbox.removeAttr('checked') or checkbox.prop("checked", false);
backgroundContainer.removeClass("checked");
}
else {
checkbox.attr('checked', 'checked').prop("checked", true);
//checkbox.attr('checked', 'checked') or checkbox.prop("checked", true);
backgroundContainer.addClass("checked");
}
}
});
Also I've got some code for making this element disabled after page loading if needed.
While debugging that works and hidden checkbox element is checked or unchecked correctly (also checkbox image is correct). Moreover, that works fine in target browser IE 10 (server-side receives correct checkbox value), but in my FireFox 29 with FireBug while debugging on form submit I see:
$("#IsSpread").attr("checked") // checked
$("#IsSpread").prop("checked") // false
and server always receives false.
Debugging on attribute change for this element gives nothing.
If I programmatically makes it checked on $(document).ready() it always sends true condition.
Thanks!

Fiddle using .attr():
if (backgroundContainer.hasClass("checked"))
{
checkbox.removeAttr('checked');
}
else
{
checkbox.attr('checked', 'checked');
}
and later:
$('#send').click(function()
{
var checked = $('#IsSpread').attr("checked") == "checked";
alert("Sending " + checked);
});
Fiddle using .prop() (actually it is strange behaviour, but works for me):
checkbox.prop('checked', checkbox.prop('checked'));
and later:
$('#send').click(function()
{
var checked = $('#IsSpread').prop("checked");
alert("Sending " + checked);
});

Related

Change radio button to checkbox displays indeterminate in chrome

I'm trying to make a radio button list appear as a checkbox list but with the benefits of a radio button list (i.e only 1 value can be submitted).
However the problem I am facing is that in Google Chrome a default value is set on 'indeterminate' while it should be set as 'false'. The first value of the list should be 'true' by default and that currently works.
How can I prevent the second value from being set on indeterminate?
The code can behave strange sometimes as refreshing the browser sometimes result in unchecking the indeterminate and sometime checking it back to indeterminate.
I haven't found a pattern in this.
$(document).ready(function() {
$("input[type=radio]:eq(0)").prop("checked", true);
$("input[type=radio]:eq(0)").data("ischecked", true);
$("input[type=radio]:eq(1)").prop("checked", false);
$("input[type=radio]:eq(1)").addClass("opt-in-radio");
$('form').on('click', ':radio', function() {
var status = $(this).data('ischecked'); //get status
status && $(this).prop("checked", false); //uncheck if checked
$(this).data('ischecked', !status); //toggle status
if (this.className == "opt-in-radio") $("input[type=radio]:eq(0)").prop("checked", !this.checked)
});
});
input[type="radio"] {
-moz-appearance: checkbox;
-webkit-appearance: checkbox;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Input checked attribute not working after confirm dialog cancel

I have a checkbox that when unchecked I want to confirm that the user intended to do so.
I am listening to the on.change event and use confirm() for the dialog. If the user clicks "Cancel" I have code to reset the checkbox. However, it is not obeying it. The 'checked="checked"' attribute is placed there as expected, but it does not appear as checked.
Here's a JSFiddle illustrating it:
https://jsfiddle.net/0tvzLbgk/9/
Below is the code.
$('#box').on('change', 'input', function() {
var $me = $(this);
if (this.checked) {
// Item has been checked, do nothing
}
else {
// Item has been unchecked
// Make sure it was not an accident
var confirmReset = confirm("Reset checkbox?");
if (confirmReset == true) {
// Okay, reset
}
else {
// Mistake, mark as checked again
$me.attr('checked', 'checked');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<input type="checkbox" />
</div>
Does anyone know why it's not following the checked attribute?
use .prop not .attr
$me.prop('checked', true);
Use prop() insead of attr() since you need to change the property here not the attribute :
$me.prop('checked', 'checked');
Hope this helps.
( Take a look to .prop() vs .attr() )
$('#box').on('change', 'input', function() {
var $me = $(this);
if (this.checked) {
// Item has been checked, do nothing
}
else {
// Item has been unchecked
// Make sure it was not an accident
var confirmReset = confirm("Reset checkbox?");
if (confirmReset == true) {
// Okay, reset
}
else {
// Mistake, mark as checked again
$me.prop('checked', 'checked');
$me.addClass('shift-input');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<input type="checkbox" />
</div>

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

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

jQuery: Problems with detecting if a checkbox is checked

I'm creating a small jQuery plugin for my CMS that styles certain form input types (just radio, checkbox at the moment). It works by hiding the original form element and placing a normal HTML element (for styling with CSS) in the input's place. It then detects actions on the element and updates the original input accordingly. Additionally, it will also work when the associated label is clicked. Here is my code:
jQuery.fn.ioForm = function() {
return this.each(function(){
//For each input element within the selector.
$('input', this).each(function() {
var type = $(this).attr('type');
//BOF: Radios and checkboxes.
if (type == 'radio' || type == 'checkbox') {
var id = $(this).attr('id');
checked = '';
if ($(this).attr('checked')) {
checked = 'checked';
}
//Add the pretty element and hide the original.
$(this).before('<span id="pretty_'+ id +'" class="'+ type +' '+ checked +'"></span>');
$(this).css({ display: 'none' });
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function() {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').removeAttr('checked');
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id).removeAttr('checked');
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
}
}
});
} //EOF: Radios and checkboxes.
});
});
};
This works great for the radio, but the checkbox seems to get stuck when clicking the checkbox label for a second time - the first click of the label successfully changes it to the appropriate state, but clicking the label again doesn't change it (however the checkbox itself still works fine). It works perfectly in IE8.
I've checked the id is correct and it is. I've also tried a few other methods I stumbled across of checking if the checkbox is checked, but they either gave the same result or failed altogether. :(
Any help would be much appreciated.
Thanks :)
Update
Here is the HTML, which is generated by a PHP class. This is after the jQuery has run and added in the span elements:
<div>
<p class="label">Test:</p>
<span id="pretty_test_published_field" class="checkbox"></span>
<input class="checkbox" id="test_published_field" name="test" type="checkbox" value="published">
<label for="test_published_field" class="radio">Published</label>
<span id="pretty_test_draft_field" class="checkbox"></span>
<input checked="checked" class="checkbox" id="test_draft_field" name="test" type="checkbox" value="draft">
<label for="test_draft_field" class="radio">Draft</label>
</div>
Just use the infallible and extremely simple DOM checked property. jQuery is inappropriate for this and apparently makes one of the simplest JavaScript tasks there is error-prone and confusing. This also goes for the id and type properties.
$('input', this).each(function() {
var type = this.type;
if (type == 'radio' || type == 'checkbox') {
var id = this.id;
var checked = this.checked ? 'checked' : '';
// Etc.
}
});
UPDATE
The default action of clicking a <label> element associated with a checkbox is to toggle the checkbox's checkedness. I haven't tried this myself with labels for hidden form elements, but perhaps the toggling is still happening because you're not preventing the browser's default click action. Try the following:
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function(evt) {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').each(function() {
this.checked = false;
});
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
evt.preventDefault();
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id)[0].checked = false;
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
}
evt.preventDefault();
}
});
i've found on the odd accassion that i need to use the alternative of:
$("#checkboxID").is(':checked');
this may or not be an alternative in your scenario, but worth noting. Also, you may have to add the 'live' event, rather than 'click' if changes to the dom are occurring. i.e.
.click(function()
to
.live('click', function()
jim
The checked attribute of a checkbox is mapped to the defaultChecked property and not to the checked property. Use the prop() method instead.
If elem is the checkbox, use:
elem.checked
or
$(elem).prop("checked")
This gives us the proper state information of the checkbox and changes as the state changes.
This seems to be the reason of confusion in many cases. So its good to keep in mind the underlying reason behind this.
Could you show us the HTML? I am looking to see if you set a value property for the checkbox in the HTML. There is a possibility that broke it.
<input type="checkbox" value="This May Break Checkbox" />
<input type="checkbox" name="This Checkbox Works" />

Categories

Resources