How to check a radio button with jQuery? - javascript

I try to check a radio button with jQuery. Here's my code:
<form>
<div id='type'>
<input type='radio' id='radio_1' name='type' value='1' />
<input type='radio' id='radio_2' name='type' value='2' />
<input type='radio' id='radio_3' name='type' value='3' />
</div>
</form>
And the JavaScript:
jQuery("#radio_1").attr('checked', true);
Doesn't work:
jQuery("input[value='1']").attr('checked', true);
Doesn't work:
jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
Doesn't work:
Do you have another idea? What am I missing?

For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.

Try this.
In this example, I'm targeting it with its input name and value
$("input[name=background][value='some value']").prop("checked",true);
Good to know: in case of multi-word value, it will work because of apostrophes, too.

Short and easy to read option:
$("#radio_1").is(":checked")
It returns true or false, so you can use it in "if" statement.

One more function prop() that is added in jQuery 1.6, that serves the same purpose.
$("#radio_1").prop("checked", true);

Try this.
To check Radio button using Value use this.
$('input[name=type][value=2]').attr('checked', true);
Or
$('input[name=type][value=2]').attr('checked', 'checked');
Or
$('input[name=type][value=2]').prop('checked', 'checked');
To check Radio button using ID use this.
$('#radio_1').attr('checked','checked');
Or
$('#radio_1').prop('checked','checked');

Use prop() mehtod
Source Link
<p>
<h5>Radio Selection</h5>
<label>
<input type="radio" name="myRadio" value="1"> Option 1
</label>
<label>
<input type="radio" name="myRadio" value="2"> Option 2
</label>
<label>
<input type="radio" name="myRadio" value="3"> Option 3
</label>
</p>
<p>
<button>Check Radio Option 2</button>
</p>
<script>
$(function () {
$("button").click(function () {
$("input:radio[value='2']").prop('checked',true);
});
});
</script>

The $.prop way is better:
$(document).ready(function () {
$("#radio_1").prop('checked', true);
});
and you can test it like the following:
$(document).ready(function () {
$("#radio_1, #radio_2", "#radio_3").change(function () {
if ($("#radio_1").is(":checked")) {
$('#div1').show();
}
else if ($("#radio_2").is(":checked")) {
$('#div2').show();
}
else
$('#div3').show();
});
});

Try This:
$("input[name=type]").val(['1']);
http://jsfiddle.net/nwo706xw/

Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments. Make sure you invoke .change(), otherwise all the "on change" bindings will ignore this event.
$("#radio_1").prop("checked", true).change();

You have to do
jQuery("#radio_1").attr('checked', 'checked');
That's the HTML attribute

Try this
$(document).ready(function(){
$("input[name='type']:radio").change(function(){
if($(this).val() == '1')
{
// do something
}
else if($(this).val() == '2')
{
// do something
}
else if($(this).val() == '3')
{
// do something
}
});
});

If property name does not work don't forget that id still exists. This answer is for people who wants to target the id here how you do.
$('input[id=element_id][value=element_value]').prop("checked",true);
Because property name does not work for me. Make sure you don't surround id and name with double/single quotations.
Cheers!

We should want to tell it is a radio button.So please try with following code.
$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);

Yes, it worked for me like a way:
$("#radio_1").attr('checked', 'checked');

This answer is thanks to Paul LeBeau in a comment. I thought I'd write it up as a proper answer since there surprisingly wasn't one.
The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:
$(".js-my-radio-button").trigger("click");
This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change on the radio button.
Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.

Try this with example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>
<script>
$(document).ready(function () {
$('#myForm').on('click', function () {
var value = $("[name=radio]:checked").val();
alert(value);
})
});
</script>

$("input[name=inputname]:radio").click(function() {
if($(this).attr("value")=="yes") {
$(".inputclassname").show();
}
if($(this).attr("value")=="no") {
$(".inputclassname").hide();
}
});

Get value:
$("[name='type'][checked]").attr("value");
Set value:
$(this).attr({"checked":true}).prop({"checked":true});
Radio Button click add attr checked:
$("[name='type']").click(function(){
$("[name='type']").removeAttr("checked");
$(this).attr({"checked":true}).prop({"checked":true});
});

Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:
$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set

I use this code:
I'm sorry for English.
var $j = jQuery.noConflict();
$j(function() {
// add handler
$j('#radio-1, #radio-2').click(function(){
// find all checked and cancel checked
$j('input:radio:checked').prop('checked', false);
// this radio add cheked
$j(this).prop('checked', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="section">
<legend>Radio buttons</legend>
<label>
<input type="radio" id="radio-1" checked>
Option one is this and that—be sure to include why it's great
</label>
<br>
<label>
<input type="radio" id="radio-2">
Option two can be something else
</label>
</fieldset>

Try this
var isChecked = $("#radio_1")[0].checked;

I've just have a similar problem, a simple solution is to just use:
.click()
Any other solution will work if you refresh radio after calling function.

function rbcitiSelction(e) {
debugger
$('#trpersonalemail').hide();
$('#trcitiemail').show();
}
function rbpersSelction(e) {
var personalEmail = $(e).val();
$('#trpersonalemail').show();
$('#trcitiemail').hide();
}
$(function() {
$("#citiEmail").prop("checked", true)
});

$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');

I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.
Example is in here:
$(function () {
$('#CostAnalysis input[type=radio]').click(function () {
var value = $(this).val();
if (value == "Supply & Lay") {
$('#ul-suplay').empty();
$('#ul-suplay').append('<fieldset data-role="controlgroup"> \
http://jsfiddle.net/m7hg2p94/4/

attr accepts two strings.
The correct way is:
jQuery("#radio_1").attr('checked', 'true');

In addition, you can check if the element is checked or not:
if ($('.myCheckbox').attr('checked'))
{
//do others stuff
}
else
{
//do others stuff
}
You can checked for unchecked element:
$('.myCheckbox').attr('checked',true) //Standards way
You can also uncheck this way:
$('.myCheckbox').removeAttr('checked')
You can checked for radio button:
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');

I used jquery-1.11.3.js
Basic Enable & disable
Tips 1: (Radio button type common Disable & Enable)
$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true);
Tips 2: ( ID selector Using prop() or attr())
$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);
jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);
Tips 3: ( Class selector Using prop() or arrt())
$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);
jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);
OTHER TIPS
$("#paytmradio").is(":checked") // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled
$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
$("input:checked", "#paytmradio").val() // get the checked value
index.html
<div class="col-md-6">
<label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
<div id="paymenttype" class="form-group" style="padding-top: inherit;">
<label class="radio-inline" class="form-control"><input type="radio" id="paytmradio" class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
<label class="radio-inline" class="form-control"><input type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
</div>
</div>

try this
$("input:checked", "#radioButton").val()
if checked returns True
if not checked returns False
jQuery v1.10.1

Some times above solutions do not work, then you can try below:
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));
Another way you can try is:
jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

Related

jQuery function not executing when checkbox changed

Here's the code I'm working on:
$(document).ready(function(){
var rewrite= function() {
$("#numback_**SQL_Value**").attr("readonly" , "readonly");
$("#numback_**SQL_Value**").attr("value" ,function() { return ($(".Report_Box").size() +**SQL_Value**;)}
)};
$(".Report_Box").click(rewrite);
});
Report_Box is a class of checkboxes later in the code. When one of the checkboxes is changed, the rewrite function is supposed to trigger.
Rewrite is supposed to lock the numback input box, turning it read only as I set the value to the number of Report_Box'es clicked.
I simplified your code to this - and it worked ok. I added the code you can use to make the input readonly...
See the description of using prop not attr here:
Setting a control to readonly using jquery 1.6 .prop()
<div>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="text" id="makero"/>
<script>
$(document).ready(function(){
var rewrite= function() {
$('#makero').val($(".Report_Box").size()).prop('readonly', true);
console.log($(".Report_Box").size());
};
$(".Report_Box").click(rewrite);
});
Could it be the typos that is causing your trouble? Try this:
$("#numback_**SQL_Value**").attr("value", function() { return($(".Report_Box").size()+"**SQL_Value**");} )};

How do I check if a file has been selected in a <input type="file"> element?

I have multiple checkboxes and a file upload input. I would like to re-enable a button if one or more checkbox's are checked AND if the input value is not null.
Here is a link to bootply
Here my html
<div class="upload-block">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="file" id="InputFile">
<button id="upload-btn" type="button blue-button"
class="btn blue-button" disabled>Submit</button>
</div>
Here is my javascript starting point:
Updated via Karl
Bind a change event on all input and then use some condition:
$('.upload-block input').change(function() {
$('#upload-btn').prop(
'disabled',
!($('.upload-block :checked').length && $('#InputFile').val()));
});
Example
This works for all the checkboxes and #InputFile has a value other than none. i.e. where a file has been chosen. However this does not work in IE9
How can I update this to work in IE9?
Bind a change event on all input and then use some condition:
$('.upload-block input').change(function() {
$('#upload-btn').prop(
'disabled',
!($('.upload-block :checked').length && $('#InputFile').val()));
});
Example
Like this:
if($('#InputFile').val().length){
//do your stuff
}
You can better use by using $.trim() method not to allow (trim) spaces:
if($.trim($('#InputFile').val()).length){
//do your stuff
}
Pure JS:
<input type="file" id="InputFile">
<button onclick="buttonSubmitClicked(event)">Submit</button>
<script>
function buttonSubmitClicked(event) {
if (!document.getElementById("InputFile").value) {
event.preventDefault();
alert("Please choose a file!");
} else {
alert("File've been chosen");
}
}
</script>
jsfiddle: check it out
$('.upload-block input').change(function() {
if ($('.upload-block :checked').length && $('#InputFile').val() ) {
$('#upload-btn').prop('disabled',false);
}
else {
$('#upload-btn').prop('disabled',true);
}
});
No need of separate selectors for checkbox and input file .upload-block input is enough to catch catch both the checkbox and file value change
I would apply the validation to all elements involved. This way changing either the checkboxes or the input will update disabled
$('#InputFile, .upload-block :checkbox').change(function(){
var isValid= $('.upload-block :checkbox:checked').length && $('#InputFile').val();
$('#upload-btn').prop('disabled',isValid);
});

How to check the radio button in which id field is blank using javascript

Here is sample html code
<div class="radioOff">
<input id="" class="hidden" type="radio">
<label for="">already a member</label>
<span class="identity">identify</span>
</div>
I tried using
document.getElementById("").checked = true;
its not working.
I can not do any change in code .
Here is that third party website where I need to select radio button
http://www.degriftour-selection.fr/login.html
Try:
$(".hidden[id='']").prop("checked",true);
DEMO here.
Can you try this,
$(function(){
$(".hidden").attr("checked", true);
});
You have used empty id="", you can add id value or you can use to get using classname.
<input id="myRadio" class="hidden" type="radio">
Jquery,
$("#myRadio").attr("checked", true);
Javascript:
document.getElementById("myRadio").checked = true;
try this
$('document').ready(function () {
$(".hidden").attr("checked", true);
});
There is no possibility to reference to empty ID because it'll be ignored in DOM.
One option is to use getElementsByClassName() to get all elements and then iterate through them. Second option (better) will be adding proper ID attribute and use it then.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div class="radioOff">
<input id="" class="hidden" type="radio">
<label for="">already a member</label>
<span class="identity">identify</span>
</div>
<script>
$('#document').ready(function () {
$(".hidden").attr("checked", true);
});
</script>
You can make use of this code in ur js:
return ($('input[type=radio]:checked').size() > 0);
Or
if(document.getElementsByClassName("hidden").checked)
You could do something like this, I believe the querySelector is supported from IE8+ and on all other major browsers.
var elem = document.querySelector(".radioOff"),
radio = (elem.firstElementChild||elem.firstChild);
radio.checked = true;
JSFiddle
Updated according to comment. To select the checkbox déjà membr you could use the JQuery selector (as the page includes JQuery 1.7.2)
$('.radioOff').find('input[type=radio]').prop('checked', true);
I have tried this and it is working perfectly.... please try from your side...
<div class="radioOff">
<input id="" class="hidden" type="radio" />
<label for="">already a member</label>
<span class="identity">identify</span>
</div>
and then after use below jquery code (you also need to add jQuery file reference)...
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$(".hidden").attr("checked", true);
});
</script>

jQuery loop each radio button not working

Very simple , this st**id tinny things will kill me.
I trying loop each radio button.
$('#recover input:radio:checked').each(function() {
alert("checked");
});
OR
function Checkform() {
var result = true;
$('#recover input[type=radio]').each(function() {
var checked = $(this).find('input:radio:checked');
if (checked.length == 0) {
result = false;
alert ("check");
}
});
return result;
}
OR
$('#recover input[type=radio]').each(function(){
if($(this).attr('checked')){
alert ("check");
}
});
HTML :
<div id="recover">
<input type="radio" name="s">
<input type="radio" name="s">
<input type="radio" name="s">
</div>
tryed also :
<div id="recover">
<form>
<input type="radio" name="s">
<input type="radio" name="s">
<input type="radio" name="s">
</form>
</div>
And:
<div id="recover">
<form>
<input type="radio" name="s" value="1">
<input type="radio" name="s" value="2">
<input type="radio" name="s" value="2">
</form>
</div>
And more combination of HTML .
And tryed more like 5 other examples of jQuery / Javascript, none working and i dont know why .
Any help please , thanks allot.
Use $(this).prop('checked') instead of $(this).attr('checked')
jsFiddle Demo
Attributes vs. Properties
...
Nevertheless, the most important concept to remember about the checked
attribute is that it does not correspond to the checked property. The
attribute actually corresponds to the defaultChecked property and
should be used only to set the initial value of the checkbox. The
checked attribute value does not change with the state of the
checkbox, while the checked property does. Therefore, the
cross-browser-compatible way to determine if a checkbox is checked is
to use the property:
if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )
The same is true for other dynamic attributes, such as selected and
value.
TRy this Demo
http://jsfiddle.net/devmgs/X6QhN/
function doCheck(){
$('#recover input[type="radio"]:checked').each(function() {
alert("checked");
});
}
use prop
because it gives true or false
and attr
gives property name like checked or not so cant use in condition
$('#recovery input[type=radio]').each(function(){
if($(this).prop('checked')){
alert ("check");
}
});
reference prop
$(document).ready(function(){
$('#recover > radio').each(function(){
if($(this).prop('checked')){
alert ("checked");
}
});
});
Try This
`
jQuery(function ()
{
if (jQuery('#recover input[name="s"]').is(':checked'))
{
alert("Checked"); }
else
{
alert("Please select an Record");
}
});`
You can access the checked property directly from the dom reference
$('#recover input[type=radio]').each(function () {
if (this.checked) { // or $(this).is(':checked')
alert("check");
}
});
If you want to process only checked items then use the :checked selector
$('#recover input[type=radio]:checked').each(function () {
alert("check");
});
Demo: Fiddle

Redirect browser based on radio button value

Is there an easier way to redirect the browser based on the selection from a radio button? This works but from what I'm reading on the world wide web there is probably an easier way.
This is my form:
<form>
<input type="radio" name="value" value="google"><span>Google</span><br>
<input type="radio" name="value" value="yahoo"><span>Yahoo</span><br>
<input type="radio" name="value" value="bing"><span>Bing</span>
This is my jquery:
$(function() {
$("input[name$='value']").click(function() {
var value = $(this).val();
if (value == 'google') {
window.location.assign("http://www.google.com");
}
else if (value == 'yahoo') {
window.location.assign("http://www.yahoo.com");
}
else if (value == 'bing') {
window.location.assign("http://www.bing.com");
}
});});
Thanks in advance
I would change the html just a bit to something like this:
<form>
<input type="radio" name="redirect" value="http://google.com"><span>Google</span><br>
<input type="radio" name="redirect" value="http://yahoo.com"><span>Yahoo</span><br>
<input type="radio" name="redirect" value="http://bing.com"><span>Bing</span>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$('input[type="radio"]').on('click', function() {
window.location = $(this).val();
});
</script>
I would also change to the .on() method since it simply makes a call to .on() anyways. The reason is that .click() simply makes a call to the .on() method creating one extra function call that isn't really necessary. Plus .on() is much more flexible!
LIVE DEMO
$(function() {
$("input[name$='value']").change(function() {
window.location.assign("http://www."+ this.value +".com");
});
});
window.location.replace would be the way to go if you require a http redirect. However, if you wish to maintain history(functioning browser back button) then either of window.location or window.location.href will be your best bet.
If its a single page application, then you can also consider window.location.hash for hashed url change.
To get the value of radio button, you can try
$('input[type=radio]').on('change', function(e) {
// preferred window location change appropriate as mentioned above
});
For a jquery based solution:
$('input[type=\'radio\']').on('change', function(e) {
$(location).attr('href', this.value);
});
I would set the url as the value of radio button.
<form>
<input type="radio" name="websiteRadio" value="http://www.google.com"><span>Google</span><br>
<input type="radio" name="websiteRadio" value="http://www.yahoo.com"><span>Yahoo</span><br>
<input type="radio" name="websiteRadio" value="http://www.bing.com"><span>Bing</span>
</form>
$(document).ready(function()
$("input[name='websiteRadio']").click(function() {
window.location = $(this).attr('value');
});
});

Categories

Resources