Checkbox irregularities with jQuery - javascript

Here's some html:
<form>
<input type="checkbox" id="check-123" />
<input type="text" id="text-123" onchange="doSomething('123')" />
</form>
And here's some javascript:
function doSomething(key)
{
var textbox = $('#text-'+key);
var checkbox = $('#check-'+key);
checkbox.attr('checked',(textbox.val()!="") );
}
My goal here is to check the checkbox anytime there's a value in the text box, and uncheck when that value is removed. This appears to work fine in the html (I can see checked="checked" being added to the checkbox), but the checkbox only appears checked the first time something is entered in the textbox.
Why would a checkbox show unchecked even if checked="checked" was added to the html?

Use element properties rather than attributes to change their state via javascript
checkbox.prop('checked',(textbox.val()!="") );
From the jQuery docs on .attr() and .prop():
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
The emphasis is jQuery's own. Only the checked property will reflect and control the checkbox's current state. The checked attribute shouldn't be used to control the checkbox state.

consider something like:
function doSomething(el) {
el.form['check-' + el.name.split('-')[1]].checked = !!el.value;
}
<form>
<input type="checkbox" name="check-123">
<input type="text" name="text-123" onchange="doSomething(this)">
</form>

I've seen some funny things with the checked attribute in IE8 and lower. In some cases I've had to set both the property and the attribute, even though modern browsers seem to be okay with just adjusting the property:
checkbox.prop('checked',textbox.val()!="");//property
Note, the following is only necessary if you come across any browser related inconsistencies.
if(textbox.val()!="")
{
checkbox.attr('checked','checked');
}
else
{
checkbox.removeAttr('checked');
}

Related

checkbox set to checked = false not working

I'm generating an HTML input with checked="false", however the checkbox is showing up checked.
I did the following in the javascript console and can't quite figure out whats going on. The resulting HTML after using .prop() to set the value to false looks the same except now the checkbox is not checked on the form.
> $(':input[checked]').prop('checked');
< true
> $(':input[checked]')
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
> $(':input[checked]').prop('checked',false);
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
I'm under the impression that I should just be setting checked="checked" OR not including the checked property at all if its false is that best practice? Either way I'd like to know what's going on in the above code.
Don't put checked="false"
You only put checked="checked" for valid XHTML, otherwise you'd do
<input type="checkbox" checked>
The browser doesn't care what value is assigned to checked attribute, as soon as it sees checked in the checkbox input tag, it's flagged as checked.
$(document).ready(function () { $(e).prop("checked", false);}
// "e" refers to button element
How to Uncheck in this case, example my code is: (see below)
if(previousHighlightedCheckbox!=null) {
console.log(sent.id, previousHighlightedCheckbox); // current checkbox and previous check box values are different.
document.getElementById(previousHighlightedCheckbox).checked = false; // still this does not uncheck previous one
}

Check a radio button with javascript

For some reason, I can't seem to figure this out.
I have some radio buttons in my html which toggles categories:
<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.
I have tried versions of this (with and without jQuery):
document.getElementById('#_1234').checked = true;
But it doesn't seem to update. I need it to visibly update so the user can see it.
Can anybody help?
EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().
Do not mix CSS/JQuery syntax (# for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().
Today, in the year 2016, it is safe to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):
document.querySelector("input[name=main-categories]:checked").value
Easiest way would probably be with jQuery, as follows:
$(document).ready(function(){
$("#_1234").attr("checked","checked");
})
This adds a new attribute "checked" (which in HTML does not need a value).
Just remember to include the jQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
By using document.getElementById() function you don't have to pass # before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo:
JSFiddle
I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:
var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
if (response["reload_mode"] == "Periodic") {
document.querySelector('input[name=reload_mode][value="Periodic"]').click();
} else if (response["reload_mode"] == "Page Bottom") {
document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
} else {
document.querySelector('input[name=reload_mode][value="Both"]').click();
}
});
Where the associated code to SAVE the value was:
reload_mode: document.querySelector('input[name=reload_mode]:checked').value
Given HTML like the following:
<input type="radio" id="periodic" name="reload_mode" value="Periodic">
<label for="periodic">Periodic</label><br>
<input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
<label for="bottom">Page Bottom</label><br>
<input type="radio" id="both" name="reload_mode" value="Both">
<label for="both">Both</label></br></br>
It seems the item.checked property of a HTML radio button cannot be changed with JavaScript in Internet Explorer, or in some older browsers.
I also tried setting the "checked" attribute, using:
item.setAttribute("checked", ""); I know the property can be set by default,
but I need just to change the checked attribute at runtime.
As a workarround, I found another method, which could be working. I had called the item.click(); method of a radio button. And the control has been selected. But the control must be already added to the HTML document, in order to receive the click event.

jQuery radio button "checked" attribute not firing

I'm trying to add text to a div based on which radio button a user checks, but it ends up firing the "else" block no matter which attribute is checked, and displaying "female" every time.
Please help!
<input type="radio" name="gender" class="gender" id="male" value="male">Male<br />
<input type="radio" name="gender" class="gender" id="female" value="female">Female<br />
$(".gender").change(function () {
if ($("#male").attr("checked")) {
$("#content").text("male");
}
else {
$("#content").text("female");
}
});
Use .prop('checked') rather than .attr('checked'). The latter is based on the HTML attribute which will always be false because it is not in the DOM. .prop can be used to check property changes that may not be visible in the DOM.
http://jsfiddle.net/Xxuh8/
Your code would have worked until jQuery 1.8 or lesser. http://jsfiddle.net/Dnd2L/
In latest versions .attr is for the attributes which was defined in the HTML and .prop is mapped to the properties of the element which is dynamic and returns the current value.
http://jsfiddle.net/Dnd2L/1/
More information about attr and prop - https://stackoverflow.com/a/5876747/297641
You don't particularly need an if since your radio buttons are grouped and no multiple choices are possible.
You might want to use this instead:
$(".gender").change(function () {
$("#content").text($(this).val());
});
JSFiddle: http://jsfiddle.net/3Lsg6/
or if your radios don't have a class use
$("input[name='gender'][checked='checked']").val();
to get the value of the checked radio. To change which is checked, put the value of the cbx you want checked in val() i.e., ...val("male");

Toggle Disabled Attribute on Input Based on Checkbox in jQuery [duplicate]

This question already has answers here:
How do i disable a submit button when checkbox is uncheck?
(7 answers)
Closed 8 years ago.
I have a checkbox that is unchecked by default and a disabled input by default.
<label class="checkbox span3"><input type="checkbox"> I am a full-time student.</label>
<input class="inputIcon span3" id="disabledInput" type="text" placeholder="Enter School Name" disabled>
I have full control over the class and id names and the site uses jQuery so can use that or plain javascript if needed.
If a user checks the box, then the "disabled" attribute should be removed from the following input. If the user unchecks it should become disabled again.
Found a several similar questions on StackOverflow but none seem to be this exact use case.
You have to assign id to checkbox to bind the click to particular checkbox,
Live Demo
<input type="checkbox" id="chk">
$("#chk").click(function(){
$("#disabledInput").attr('disabled', !this.checked)
});
First give your checkbox an id
<input id='cbFullTime' type="checkbox">
Then in its click handler, fetch the textbox, and set its disabled property to the inverse of the current value of the checkbox's checked property:
$('#cbFullTime').click(function() {
var cbIsChecked = $(this).prop('checked');
$('#disabledInput').prop('disabled', !cbIsChecked);
});
Note that, while using attr and removeAttr will work (assuming you're not using exactly jQuery 1.6), using the prop function is a bit simpler, and a bit more correct. For more information, check out this link
Try the below
$(".checkbox").find("checkbox").click(function() {
$('#disabledInput').prop('disabled', $(this).prop('checked'));
});

Add attribute 'checked' on click jquery

I've been trying to figure out how to add the attribute "checked" to a checkbox on click. The reason I want to do this is so if I check off a checkbox; I can have my local storage save that as the html so when the page refreshes it notices the checkbox is checked. As of right now if I check it off, it fades the parent, but if I save and reload it stays faded but the checkbox is unchecked.
I've tried doing $(this).attr('checked'); but it does not seem to want to add checked.
EDIT:
After reading comments it seems i wasn't being clear.
My default input tag is:
<input type="checkbox" class="done">
I need it top be so when I click the checkbox, it adds "checked" to the end of that. Ex:
<input type="checkbox" class="done" checked>
I need it to do this so when I save the html to local storage, when it loads, it renders the checkbox as checked.
$(".done").live("click", function(){
if($(this).parent().find('.editor').is(':visible') ) {
var editvar = $(this).parent().find('input[name="tester"]').val();
$(this).parent().find('.editor').fadeOut('slow');
$(this).parent().find('.content').text(editvar);
$(this).parent().find('.content').fadeIn('slow');
}
if ($(this).is(':checked')) {
$(this).parent().fadeTo('slow', 0.5);
$(this).attr('checked'); //This line
}else{
$(this).parent().fadeTo('slow', 1);
$(this).removeAttr('checked');
}
});
$( this ).attr( 'checked', 'checked' )
just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />
Edit:
Based on comments, a more appropriate manipulation would be:
$( this ).attr( 'checked', true )
And a straight javascript method, more appropriate and efficient:
this.checked = true;
Thanks #Andy E for that.
It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr() method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]
IE has some problems with the DOM setAttribute method but in this case it should be fine:
this.setAttribute("checked", "checked");
In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked attribute, you need to set the checked property as well:
this.setAttribute("checked", "checked");
this.checked = true;
To uncheck the checkbox and remove the attribute, do the following:
this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().
A simple answer is to add checked attributes within a checkbox:
$('input[id='+$(this).attr("id")+']').attr("checked", "checked");
use this code
var sid = $(this);
sid.attr('checked','checked');

Categories