Get values of all checked radio buttons using JQuery - javascript

Using JQuery I am trying to perform validation and also get the values of all the dynamically generated Radio buttons in the page.
I have 10 questions on my page and each question has a Radio button group(YES/NO).
when click in the radio button i want to send it's value to database for the question, this is my code
<p>Question 1</p>
<input id="1_1" type="radio" name="1" value="Yes" />
<input id="1_2" type="radio" name="1" value="NO" />
i searched in google and found this code
$('input[name=radioName]:checked', '#myForm').val()
But I don't know what is the right way to use it ?

As per your HTML structure try this :-
var arr = []; // take an array to store values
$('input[type="radio"][name="1"]:checked').each(function(){
arr.push($(this).val()); //push values in array
});

If you want the values of all <radio> you can do
var ans = $('[name=1]:checked').map(funciton(){
return $(this).val();
}).get();

Related

jQuery Ajax checkbox value

I have checkboxes on my page for which I would like to send their state back to the database via ajax. I know how to use jquery with ajax and how to work with SELECT and OPTIONS, but I don't know to do the same things with several checkboxes and how to get the value from them.
Everything works when id is attached to one checkbox, but when i attach id to several checkboxes it doen'twork(except first check box)
Any ideas?
my code looks like this->
<form>
<div class="checkbox" >
<label><input type="checkbox" value="1" id="item">что то</label>
<label><input type="checkbox" value="1" id="item">Шорты</label>
<label><input type="checkbox" value="3" id="item">Классическая</label>
</div>
</form>
<script>
$(document).ready(function () {
$('#item').on('click',function(){
var name = $('#item').val();
$.post('load.php', {name:name}, function(data){
$('#name-data').html(data);
});
});
});
</script>
Use a class. Ids are expected to be unique on a single page. Classes are used to group elements together.
<tag id="a">A</tag><tag id="a">B</tag> $('#a')
becomes
<tag class="a">A</tag><tag class="a">B</tag> $('.a')
Id should be unique you can use class instead of Id.

Edit data from database in form when using radio button

I have a database with some information which i then show using php and javascript
If i click on edit a javascript form opens up and i can edit the shown information. This all works great but instead of an input field (in which i show the data currently inside of the database) i would like to use a radio button.
So i need to make a radio button with the values Yes and No and if the information inside the database = 0 i want to show no and 1 to show yes
When using an input field i see yes or no (depending on what is stored inside the database) how can i use a radio button in this scenario.
my input field looks like this
<input type='text' class='input' name='test_" +id+ "' value='"+test+"' />
Considering you have html like this:
<form name="yesnoform">
<label for="no">No</label><input value="no" type="radio" name="yesno" id="no"/>
<label for="yes">Yes</label><input value="yes" type="radio" name="yesno" id="yes"/>
</form>
you can use this code to select correct radio button:
var fromDB = 0;
document.yesnoform.yesno[fromDB].checked=true;
If you want yes radio button first:
<form name="yesnoform">
<label for="yes">Yes</label><input value="yes" type="radio" name="yesno" id="yes"/>
<label for="no">No</label><input value="no" type="radio" name="yesno" id="no"/>
</form>
then use this:
var fromDB = 0;
var value = fromDB === 0 ? 1 : 0;
document.yesnoform.yesno[value].checked=true;
Here is JSBin: https://jsbin.com/fijiteruba/edit?html,js,output
Hope this helps.

jQuery else clause not working [duplicate]

I have 3 radio buttons in my web page, like below:
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
$("<radiobutton name attribute>").click(function(){});
Please tell me how to solve this problem.
This should do it, all of this is in the documentation, which has a very similar example to this:
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.
To determine which radio button is checked, try this:
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.
$('input:radio[name=theme]:checked').val();
another way
$('input:radio[name=theme]').filter(":checked").val()
This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.
$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks
Adnan
For anyone who doesn't want to include a library to do something really simple:
document.querySelector('[name="theme"]:checked').value;
jsfiddle
For a performance overview of the current answers check here
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio with [type=radio].
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
http://jsfiddle.net/h6ye7/67/
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
If you want a true/false value, use this:
$("input:radio[name=theme]").is(":checked")
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:
$("input:radio[type=radio]").click(function() {
var value = $(this).val();
alert(value);
});
Cheers!
can also use a CSS class to define the range of radio buttons and then use the following to determine the value
$('.radio_check:checked').val()
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() {
if($(this).is(':checked'))
alert($(this).val());
});
Hope it helps..
$('input:radio[name=theme]').bind(
'click',
function(){
$(this).val();
});
You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.
You create RadioButton control in ASP.NET as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});

Get value of multiple choices checkboxes Javascript

I'm using the onsubmit event on a form to verify it before it is sent. I'm having issues getting the value of checkboxes that allows multiple choice.
Html:
<input type="checkbox" name="question5[]" value="1" />
<input type="checkbox" name="question5[]" value="2" />
Javascript:
var form = document.forms['questionnaire'];
var q5 = form.elements["question5"].value;
When I try to get the value of this question I'm not able to retrieve it the same way I did for the other fields. I'm wondering what is the correct way to get the value of those checkboxes since I can't retrieve it like a radio or text input.
The name of the field is question5[] not question5 and since you have multiple of them, you will get a NodeList (which is like an Array) back, not a single Element.

Radio Button Control in jquery

I'm new to Web development and jQuery.
I'm trying to build an ASPX page with two RadioButton controls that must perform the following actions:
On page load, one of the two must be selected depending on a flag from an object on the ASPX page. Lets call it customer.Id. If the Id is true, select RadioButton one must be set else select RadioButton 2 must be set.
At any point after page load the user selects a RadioButton, the other must be deselected.
When RadioButton two is clicked, hide a Table named "employee table" and when RadioButton one is clicked, show that Table.
Can anyone please tell me how I can get this functionality in jQuery functions?
Not sure about .NET but in Classic ASP you would write a variable like this <%=customerID%>.
In jQuery, I think you can do something like this:
<input type="radio" id="radio1"> Yes
<input type="radio" id="radio2"> No
<table border="1" id="employeeTable">
<tr><td>This is the table</td></tr>
</table>
... and then some jQuery:
$(document).ready(function() {
var customerID = <%=customerID%> // asp variable
if (customerID != "") {
$('#radio1').prop('checked', 'checked');
} else {
$('#radio2').prop('checked', 'checked');
}
$('#radio1').click(function() {
$('#employeeTable').fadeIn('fast');
})
$('#radio2').click(function() {
$('#employeeTable').fadeOut('fast');
})
})
You can have a look/play here: http://jsfiddle.net/qcLtX/7/
Try changing the customerID value to nothing, like var customerID = "".
Good luck
UPDATE
Where I have used .prop: If you are using jQuery version 1.6 or greater, you should use .prop, otherwise, use .attr.
Radio buttons are grouped by their name attribute, like so (source).
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
If the radio buttons are grouped, then selecting any one of them automatically delselects all the others in that group.
So the buttons cannot have a distinct name. If you want to distinguish between radio buttons (without referring the their value), you should add an id.
<input type="radio" name="sex" id="m" value="male" />
You can set the selected radio button on page load declaratively in markup, or using jquery.
Declarative version:
<input type="radio" checked="checked" name="sex" value="male" />
jQuery:
$(document).ready(function(){
$("#m").attr("checked", "checked");
});

Categories