jQuery - Checking Check Box Values (Chaining jQuery functions Vs If Statment) - javascript

I have multiple check boxes and wanting to get an overall value for them all.
For example if one is checked then value is true/selected.
If none are checked then false/unchecked.
My HTML is:
<input id="one" type="checkbox">
<input id="two" type="checkbox">
<input id="three" type="checkbox">
<input id="four" type="checkbox">
<button onclick="check();">Is checked (jQuery Chained)</button>
<button onclick="check2();">Is checked(Big If Statement)</button>
My JavaScript/jQuery is:
function check() {
var booleee = $('#one,#two,#three,#four').attr('checked');
alert("Checked: " + booleee);
}
function check2() {
if ($('#one').attr('checked') || $('#two').attr('checked') || $('#three').attr('checked') || $('#four').attr('checked')) {
alert("Checked: true");
}
alert("Checked: false");
}
Js Fiddle: Click Here
Please note, I have solved this problem. This question is more to help me understand why my checked2() function works and my check() doesnt.

var booleee = $('#one,#two,#three,#four').attr('checked'); checks only whether the first (in this case #one) checkbox is checked.
From the doc for attr
Get the value of an attribute for the first element in the set of
matched elements.
it should be
var booleee = $('#one,#two,#three,#four').filter(':checked').length > 0;
Also in new versions(>1.6) you need to use the property 'checked' (.prop('checked')) instead of attr in the alternative you have a :checked filter so .is(':checked').

Because it's not checking all the elements in the selector.
to make it work
function check() {
var booleee =$("input:checkbox:checked").length > 0;
alert("Checked: " + booleee);
}
To more specific selection add form id in selector
DEMO

A better approach: http://jsfiddle.net/arvind07/ZP78F/
function check() {
var checks = $('input:checkbox');
var checked = 0;
checks.each(function() {
if ($(this).is(":checked")) {
checked = 1;
return false;
}
});
if (checked) {
alert("Checked");
} else {
alert("Not checked");
}
}

in html set checked property
<input id="one" type="checkbox" checked="checked">
<input id="two" type="checkbox" checked="checked">
<input id="three" type="checkbox" checked="checked">
<input id="four" type="checkbox" checked="checked">
you not defined checked so it show undefined because it cant read this attribute and when you call second function then only false come in alert because their checkbox checked attribute not find
see demo

var checked = $(':checkbox:checked').length > 0;

Related

JQuery selective hiding not working

I'm trying to create a menu where each element has its own checkbox. On selecting the sorting button ( for now it is a checkbox here ), the menu is supposed to show only the elements who already have the checkboxes active ( this is done by manually clicking the checkbox of the element and keeping it active)
Here's my HTML code
<input type= "checkbox" class="toggler" id="clicked" onclick="tclick()" >click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello3</p>
And here is my Jquery
function but_clicked(){
// alert("Hello, checkbox clicked");
if(this.id=="active"){
this.id="inactive";
console.log(this.id);}
else{
this.id="active";
console.log(this.id);
}
}
function tclick(){
//alert("Toggler clicked");
if(this.id=="clicked"){
this.id="empty";
console.log(this.id);
}
else{
this.id="clicked";
console.log(this.id);
}
}
$(document).ready(function(){
$('.toggler').change(function(){
if($(this).is('clicked')){
$('#inactive').hide();
$('#active').show();
}
else{
$('#active').show();
$('#inactive').show();
}
})
});
But when I am setting the Click here to sort checkbox, the others are not being hidden regardless of each of their checkbox status. I feel like it's a very silly mistake that I am doing, please help.
First of all id property must be unique in the DOM, so you cannot have multiple elements with id active or inactive.
This is the main problem as $('#inactive') will only return the first element it matches (since it should be unique).
Furthermore, checkboxes have a checked property that signifies if they are checked or not so all your code could just check that instead of altering the id all the time.
Last, you should use label tags for the text instead of p so that clicking on the text will also check/uncheck the checkbox.
(oh, the .toggler checkbox actually filters, and not sorts ,the others)
So taking all issues into account you could simplify your code to
$(document).ready(function() {
$('.toggler').change(function() {
if (this.checked) {
$('.grouped').parent().hide();
$('.grouped:checked').parent().show();
} else {
$('.grouped').parent().show();
}
})
});
label{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="toggler">click here to filter</label></p>
<label><input type="checkbox" class="grouped">Hello1</label>
<label><input type="checkbox" class="grouped">Hello2</label>
<label><input type="checkbox" class="grouped">Hello3</label>
Your code can be way easier with some little tricks.
First thing, do not change IDs at run time, it's a bad practise.
Checkboxes have properties like checked, which evaluates to false or true when tested with this.checked.
<input type= "checkbox" class="toggler" id="click_to_toggle" >click here to toggle
<p class="item"><input type="checkbox" >Hello1</p>
<p class="item"><input type="checkbox" >Hello2</p>
<p class="item"><input type="checkbox">Hello3</p>
And this is the only JS you need:
$('#click_to_toggle').on('change', function(){
if( this.checked ){
$('.item').hide();
$('.item input:checked').each(function(){
$(this).closest('.item').show();
});
} else {
$('.item').show();
}
});
Working fiddle HERE
Pass in the element itself this this in the html, and just use that parameter in your javascript instead of this. Also you need to use .is with the :checked selector instead of just clicked. I also change changed .changed() to .clicked() since they are the same event in this case. You also might want to consider changing the id of inactive/active to be a class since all ids must be unique.
function but_clicked(e) {
if (e.id == "active") {
e.id = "inactive";
console.log(e.id);
} else {
e.id = "active";
console.log(e.id);
}
}
function tclick(e) {
if (e.id == "clicked") {
e.id = "empty";
console.log(e.id);
} else {
e.id = "clicked";
console.log(e.id);
}
}
$(document).ready(function() {
$('.toggler').click(function() {
if($('.toggler').is(':checked')) {
$('#inactive').hide();
$('#active').show();
} else {
$('#active').show();
$('#inactive').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="toggler" id="clicked" onclick="tclick(this)">click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello3</p>

jquery - show textbox when checkbox checked

I have this form
<form action="">
<div id="opwp_woo_tickets">
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</form>
As of now, I'm using this jquery code to show textbox when checkbox checked.
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $('div.max_tickets').show();
else $('div.max_tickets').hide();
}).change();
});
It works fine, but it shows all textboxes when checked.
Can someone help me to fix it?
Here is the demo of my problem.
http://codepen.io/mistergiri/pen/spBhD
As your dividers are placed next to your checkboxes, you simply need to use jQuery's next() method to select the correct elements:
if ($(this).is(':checked'))
$(this).next('div.max_tickets').show();
else
$(this).next('div.max_tickets').hide();
Updated Codepen demo.
From the documentation (linked above), the next() method selects:
...the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Here we're selecting the next div.max_tickets element. However in your case just using next() with no parameters would suffice.
Assuming markup will stay in same order can use next()
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
$(this).next()[ this.checked ? 'show' : 'hide']();
}).change();
});
Change:
if ($(this).is(':checked')) $('div.max_tickets').show();
To:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
jsFiddle example here
Maybe try selecting the next element only?
change:
if ($(this).is(':checked')) $('div.max_tickets').show();
to:
if ($(this).is(':checked')) $(this).next('div.max_tickets').show();
Put a div across your checkbox and text box
<form action="">
<div id="opwp_woo_tickets">
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][0][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][0][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][1][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][1][maxtickets]">
</div>
</div>
<div>
<input type="checkbox" class="maxtickets_enable_cb" name="opwp_wootickets[tickets][2][enable]">
<div class="max_tickets">
<input type="text" name="opwp_wootickets[tickets][2][maxtickets]">
</div>
</div>
</div>
</form>
and replace your jquery code with this one below,
jQuery(document).ready(function($) {
$('input.maxtickets_enable_cb').change(function(){
if ($(this).is(':checked')) $(this).parent().children('div.max_tickets').show();
else $(this).parent().children('div.max_tickets').hide();
}).change();
});
I have tested it and it works.
While you may need a JavaScript solution for other reasons, it's worth noting that this can be achieved with pure CSS:
input + div.max_tickets {
display: none;
}
input:checked + div.max_tickets {
display: block;
}
JS Fiddle demo.
Or, with jQuery, the simplest approach seems to be:
// binds the change event-handler to all inputs of type="checkbox"
$('input[type="checkbox"]').change(function(){
/* finds the next element with the class 'max_tickets',
shows the div if the checkbox is checked,
hides it if the checkbox is not checked:
*/
$(this).next('.max_tickets').toggle(this.checked);
// triggers the change-event on page-load, to show/hide as appropriate:
}).change();
JS Fiddle demo.
Reference:
CSS:
:checked pseudo-class.
jQuery:
change().
next().
toggle().
protected void EnableTextBox()
{
int count = int.Parse(GridView1.Rows.Count.ToString());
for (int i = 0; i < count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBox cb1 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox2");
CheckBox cb2 = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox3");
TextBox tb = (TextBox)GridView1.Rows[i].Cells[4].FindControl("txtration");
TextBox tb1 = (TextBox)GridView1.Rows[i].Cells[5].FindControl("txtjob");
TextBox tb2 = (TextBox)GridView1.Rows[i].Cells[6].FindControl("txtaadhar");
if (cb.Checked == true)
{
tb.Visible = true;
}
else
{
tb.Visible = false;
}
if (cb1.Checked == true)
{
tb1.Visible = true;
}
else
{
tb1.Visible = false;
}
if (cb2.Checked == true)
{
tb2.Visible = true;
}
else
{
tb2.Visible = false;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
EnableTextBox();
}

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

Check to see if none of the checkboxes was checked in jquery

I have two checkboxes and one of the checkboxes must be checked. I can see that it's right, no syntax errors. What should be made to my code to check if none of the checkboxes were checked?
HTML :
<input type="checkbox" value="aa" class="first" name="a"> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b"> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
JavaScript:
$('button').on('click',function(){
if( $(".first:not(:checked)") && $(".second:not(:checked)") ){
$('.error').text('You must select atleast one!');
}else
$('.error').hide();
});
Example : http://jsfiddle.net/ptbTq/
Check this fiddle: http://jsfiddle.net/692Dx/
Checking code:
if($('input[type="checkbox"]:checked').length == 0) {
alert('none checked');
}
You are using selectors which do not return boolean values which is what you need when writing an if condition. Here's what you could do:
$('button').on('click',function() {
if(!$(".first").is(":checked") && !$(".second").is(":checked")) {
$('.error').text('You must select atleast one!').show();
} else {
$('.error').hide();
}
});
or if you prefer and think it could be more readable you could invert the condiciton:
$('button').on('click',function() {
if($(".first").is(":checked") || $(".second").is(":checked")) {
$('.error').hide();
} else {
$('.error').text('You must select atleast one!').show();
}
});
Also notice that you need to .show() the error message in the first case as you are hiding it in the second.
And here's a live demo.
Short:
$("input[type=checkbox]").is(":checked")
returns true if:
one of your checkboxes - from the selector ("input[type=checkbox]") - is checked.
else return false
and in your case:
$(".first, .second").is(":checked")
Do something at least one of your checkboxes is checked
Put the same class on both checkboxes and you can do something like
if ($(':checkbox.the_class:checked').length > 0) {
// at least one checkbox is checked
// ...
}
The best would be to put your checkboxes inside a div with an unique ID so you can verify all the checkboxes in there, so your code will work in all cases. Even when adding new checkboxes to the div later on.
<div id="cb">
<input type="checkbox" value="aa" class="first" name="a" /> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b" /> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
</div>
Your JQuery:
$('button').click(function() {
var checked_one = $('div#cb input[type="checkbox"]').is(':checked');
if (!checked_one )
$('.error').text('You must select atleast one!');
else
$('.error').hide();
});
Live demo can be seen here: http://jsfiddle.net/ptbTq/15/

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources