I am writing some Javascript for an Apache Wicket page and am trying to create a "Select All" checkbox that, when checked, will check all of the other checkboxes and then disable them. Similarly, when dechecked, it will enable and uncheck all of the checkboxes. This checkbox will not be updated by the rest (that is, selecting all of the other checkboxes will not select the Select All box).
I can accomplish what I want using checkbox.checked = selectAll.checked but it doesn't seem to pass in a click event, which I need for some functionality in Wicket. Using checkbox.click() gives me the click events I need but doesn't seem to run after re-enabling the checkboxes.
var selectAll = document.getElementById("all");
function checkbox_changed() {
checkboxes = document.getElementsByName('foo');
for (var i in checkboxes) {
var checkbox = checkboxes[i];
checkbox.disabled = false;
if (checkbox.checked !== selectAll.checked) {
//checkbox.checked = selectAll.checked;
checkbox.click();
}
if (selectAll.checked) {
checkbox.disabled = true;
}
}
}
<form>
<input type="checkbox" id="all" onchange="checkbox_changed()">Select All
<br>
<br>
<input type="checkbox" name="foo">One
<br>
<input type="checkbox" name="foo">Two
<br>
<input type="checkbox" name="foo">Three
<br>
<input type="checkbox" name="foo">Four
<br>
</form>
In case its easier, here is a jsfiddle of the above: https://jsfiddle.net/ytggu5as/
EDIT: I just realized this is only happening in Firefox (I'm using 39.0) and updated the question. It seems to be okay in Chrome and Safari (haven't tested any others). Any idea why this is happening and how to get around it? If not, is there a better alternative to .click() than just using .checked?
The fact that calling click() after reenabling the checkbox doesn't work seems to be a bug in Firefox.
You could work around the bug by setting disabled=false in a first pass, then inside a setTimeout(..., 0) iterate over the checkboxes again and call click() as needed.
Related
What is a good way to continously check if a Checkbox is checked or not.
This checks wether it is checked or not.
I thought of creating an interval but I do not like that.
if(checkboxPencil.checked)
You basically have two choices:
Use an event handler for the change event
Poll using setInterval or similar
Of the two, #1 is by far the better option unless you have a really good reason for not using the event.
Here's an example of #1:
// The selector can be any valid CSS selector identifying the checkbox
document.querySelector("input[type=checkbox]").addEventListener("change", function() {
console.log("New value is: " + this.checked);
}, false);
<label>
<input type="checkbox">
Checkbox
</label>
Take a look at the the onchange Event which is supported in all modern browsers.
Whatever functionality you wish to do if the checkbox is checked, you'll be able to do from an onchange Event handler. For example:
function changeStatus(o) {
document.getElementById('status').innerText = o.checked;
}
<input id="check" type="checkbox" onchange="changeStatus(this)" />
<span id="status">false</span>
The requirment is that if Reset button is clicked,
All radio buttons have to be enabled.
The Daily radio button has to be checked.
These codes works well on IE, Chrome, and Safari. But not work on Firefox!
In firefox,[document.getElementById('day').click(); on JAVASCRIPT
7th line.]
won't work well by the following steps.
Click disable button (to disable all radio buttons.)
Click reset (to enable all radio buttons and daily radio button is checked.)
Here the Daily radio button is not checked on Firefox.
(There are some other procedures if the radio buttons are changed.So I need to trigger onclick event of the Daily radio button)
HTML
<input type="radio" name="sumType" value="1" id="day" tabindex="1">Daily
<input type="radio" name="sumType" value="2" id="month" tabindex="2" checked>Monthly
<input type="button" value="Disable" onclick="disableRadio()" id="rd1"/>
<input type="button" value="Reset" onclick="init()" id="rd2"/>
Javascript
function disableRadio(){
$("input[type=radio]").attr('disabled','disabled');
}
function init(){
$("input[type=radio]").removeAttr("disabled");
document.getElementById('day').click();
}
DEMO >> https://jsfiddle.net/znjjjd6e/10/
If you just need to check the day radio,
$('#day')[0].click();
Fiddle
or
document.getElementById('day').checked = true;
document.getElementById('day').click() won't trigger the actual mouse click event of the radio, it triggers the onclick handler - Refer.
Also, usage of prop() is better as suggested by Rayon
To checked any radio button simply do:
DEMO: https://jsfiddle.net/hj5qw8w0/
function init(){
$("input[type=radio]").removeAttr("disabled");
el = window.document.getElementById('day'); // add this lines
el.checked = true; // add this lines - it will checked the day radio button
}
You need to replace the javascript statement:-
document.getElementById('day').click();
with
document.getElementById('day').checked=true;
and the code will work in Firefox also
Firefox wont support click().You can check SO question
So this document.getElementById('day').click(); will not work
Since you are using jquery you can use either of this
function init(){
$("input[type=radio]").removeAttr("disabled");
//$('#day').trigger('click'); // either use this
$('#day').attr('checked',true); // or you can also use this
}
check for Demo
I've a problem wherein a checkbox is set so that checking it will enable and select a radio button that is usually disabled, and unchecking it will disable that same radio (and select another default option).
In Firefox, checking the box will enable the radio as expected, will then trigger the bound event to log "checked_radio click" to the console, but will not visually change the radio button or set the radio's checked property to true. The now-enabled radio can be selected as normal afterwards (triggering the click event a second time).
The reverse - unchecking the box correctly disables the radio and selects the default - works as expected.
It all works as intended in both Chrome and Safari, and seems to be failing regardless of which version of jQuery I use. Firefox version 28 and 29 have show then problem, no other versions tried. All attempts on Mac OS X Mavericks.
So, what's going wrong here?
I've reproduced the problem in a minimal state in a JS Fiddle, the code of which is reproduced below as well for completeness.
Expected behaviour:
When you check the checkbox, the 'checked radio' option should become enabled and selected (the selection here is what is failing for me in Firefox).
When you uncheck the checkbox the 'unchecked radio' option should be selected, while the 'checked radio' option should become disabled.
The HTML:
<label>
<input id="checkbox" type="checkbox">
Control Checkbox
</label>
<br>
<label>
<input id="checked_radio" name="radios" type="radio" value="on">
</label>
Checked Radio
<br>
<label>
<input id="unchecked_radio" name="radios" type="radio" value="off" checked>
Unchecked Radio
</label>
And the accompanying JavaScript:
var checkbox = null
var checked_radio = null
var unchecked_radio = null
$(document).ready(function(){
checkbox = $('#checkbox')
checked_radio = $('#checked_radio')
unchecked_radio = $('#unchecked_radio')
checkbox.click(update_radio)
checked_radio.click(function(){ console.log('checked_radio click') })
unchecked_radio.click(function(){ console.log('unchecked_radio click') })
update_radio()
})
function update_radio() {
if(checkbox.prop('checked')) {
checked_radio.prop('disabled', false)
checked_radio.click()
} else {
unchecked_radio.click()
checked_radio.prop('disabled', true)
}
}
Use checked_radio.prop('checked', true) instead of checked_radio.click()
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.
I had the following check in my jQuery which I thought was working fine to see if a radio button was checked.
if ($("input[#name='companyType']:checked").attr('id') == "primary") {
...
}
Here's the radiobuttons:
<p>
<label>Company Type:</label>
<label for="primary"><input onclick="javascript: $('#sec').hide('slow');$('#primary_company').find('option:first').attr('selected','selected');" type="radio" name="companyType" id="primary" checked />Primary</label>
<label for="secondary"><input onclick="javascript: $('#sec').show('slow');" type="radio" name="companyType" id="secondary" />Subsidiary</label>
</p>
Then, it suddenly stopped working (or so I thought). I did some debugging and finally realized that it was returning an id of "approved_status". Elsewhere on my form I have a checkbox called "approved_status". I realized that when I originally tested this, I must have testing it on records where approved_status is false. And, now most of my approved_statuses are true/checked.
I changed the code to this:
var id = $("input:radio[#name='companyType']:checked").attr('id');
alert(id);
if (id == "primary") {
And it's now properly returning "primary" or "secondary" as the id.
So, it is working, but it seems that it's not checking the name at all and now just checking radio buttons. I just want to know for future use, what's wrong with the original code b/c I can see possibly having 2 different radio sets on a page and then my new fix probably wouldn't work. Thanks!
Try this:
var id = $("input[name='companyType']:checked").attr('id');
alert(id);
if (id == "primary") {