Check a radio button with javascript - 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.

Related

Checkbox irregularities with jQuery

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');
}

How to check "checkbox" dynamically - jQuery Mobile

With HTML a checkbox is created like this:
<form>
<input type="checkbox" id="category1">Category1<br>
</form>
With javascript we can check the checkbox like this:
$("#category1")[0].checked = true
Now I am trying to create the same page with jquery-mobile. The checkbox looks like this:
<form>
<label>
<input name="checkbox-0 " type="checkbox">Check me
</label>
</form>
Why is there is no id here? Is the name the id? Should I delete the attribute name and create one with the name id?
How can I check this checkbox here with Javascript/jQuery?
I tried the code above, but it doesn't seem to work for this checkbox.
You need to refresh it after changing its' .prop, using .checkboxradio('refresh'). This is the correct way to check checkbox/radio in jQuery Mobile.
Demo
$('.selector').prop('checked', true).checkboxradio('refresh');
Reference: jQuery Mobile API
You can do:
$('input[name="checkbox-0"]').prop("checked", true).checkboxradio('refresh'); //sets the checkbox
var isChecked = $('input[name="checkbox-0"]').prop("checked"); //gets the status
Straight from the jQ Mobile docs:
$("input[type='checkbox']").attr("checked",true);
With the solution from #Omar I get the error:
Uncaught Error: cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'
I actually had a flipswitch checkbox:
<div class="some-checkbox-area">
<input type="checkbox" data-role="flipswitch" name="flip-checkbox-lesson-complete"
data-on-text="Complete" data-off-text="Incomplete" data-wrapper-class="custom-size-flipswitch">
</div>
and found the solution was:
$("div.ui-page-active div.some-checkbox-area div.ui-flipswitch input[type=checkbox]").attr("checked", true).flipswitch( "refresh" )
Notes
I don't usually specify ids for page content as jQuery Mobile loads multiple div.ui-page content into a single HTML page for performance. I therefore never really understood how I could use id if it might then occur more than once in the HTML body (maybe someone can clarify this).
If I use prop rather than attr the switch goes into an infinite flipping loop! I didn't investigate further...

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'));
});

Radio button on/off trigger works only one way

So this is the dumbest thing I've struggled with in awhile. I cannot get the state of a simple radio button set to toggle something on the page.
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" id="completeSw" name="completeSw" value="0" checked="checked"/>No<br/>
So you can see here an extremely simple yes/no radio button set to toggle an action. It needs to serve two purposes: to flag a yes/no value (1/0) in the POST data, and ideally trigger an action on the page using JS/jQuery. I'm having trouble with the latter.
The default state is "No"; if I click "Yes" I can retrieve an onchange or onclick event state and make something happen. However, this is a one-way switch; I cannot retrieve a state going back to the "No" selector once I've gone to "Yes". What I need to be able to do is show / hide an element on the page depending on what choice they've made in this radio set. If I click "Yes", I can trigger the action and see the page change. Once I click "No", however, it acts as if there was no state change and I cannot perform an action i.e. hide the element again.
I've tried variations on retrieving the "checked" state, the radio pair value, etc, e.g.
$("#completeSw").change(function(e){
alert( $(this).attr("checked") ); // only triggers when "Yes" is selected
});
Perhaps I should not be using a yes/no radio pair, but instead be using a single checkbox? Seems more user-friendly and elegant this way (radio buttons) to me.
IDs must be unique, so it will only ever find the first one on your page. Use a class instead.
Really, ID's must be unique, but you don't need 2 ID's. You'll only monitor changes in one radio. For example - "Yes" value
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" name="completeSw" value="0" checked="checked"/>No<br/>
And the you'll process the checked attribute of only this element. True - "Yes", False - "No"
Some browsers don't do anything when alert(message), message=null. And since an unchecked field has no checked-attribute, that could be the thing :).
Try:
alert('Checked: '+$(this).attr("checked"));
This is separate, but you're kinda using the label wrong also. The label is meant to extend the click area so someone could click on the word 'Yes' and the radio button will activate. Hopefully this helps you out a little.
<span>Completed?</span>
<input type="radio" id="completeSwYes" name="completeSw" value="1"/><label for="completeSwYes">Yes</label>
<input type="radio" id="completeSwNo" name="completeSw" value="0" checked="checked"/><label for="completeSwNo">No</label><br/>
<script type="text/javascript" charset="utf-8">
// If the radio button value is one then this evaluates to true.
var completeSW;
jQuery("input[type='radio'][name='completeSw']").change(function() {
completeSW = (jQuery(this).val() == 1);
alert("completeSW checked? " + completeSW);
});
</script>

Categories