Getting the selected radio without using "Id" but "name" - javascript

I was trying to get selected radio button by using "document.getElementByName('nameOfradio')" because all of the radio buttons share the same name. But, nothing happened. I tried the same thing with document.getElementById('nameOfradio') and worked well.However, I had to give unique id for all of the radio buttons. So that, it turns ugly when i have 20 radio buttons. As a result, what I wanted is making a shortcut. How can i get the value of selected radio button by using their "name"? Codes;
Html
<input type="radio" name="nameOfradio" value="onm1" /> 1
<input type="radio" name="nameOfradio" value="onm2" /> 2
<input type='button' onclick='radio3()' value='Submit' />
</form>
Ajax(relavant part of radio3())
var radioPushed = document.getElementByName('nameOfradio').value;
var queryString = "?radioPushed=" + radioPushed;//to send the value to another file
ajaxRequest.open("GET", "radio_display.php" + queryString, true);
ajaxRequest.send(null);
As i said document.getElementById worked but it requires too much work:( How can i make it simplier by using common feature of radio buttons, instead of giving them unique id? A short explanation why i could not make it would be very helpful(new in javascript and ajax)

This line:
document.getElementByName('nameOfradio').value
should be:
document.querySelector('input[name=nameOfradio]:checked').value;
using querySelector
Note that CSS pseudo-classes are accessed by a colon (:).

document.querySelector('input[name=nameOfRadio]:checked').value
Eg:-
<form>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
document.querySelector('input[name=gender]:checked').value
Also, you can add a checked attribute to a default radio button among the group of radio buttons if needed
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other

Save yourself some pain in the later js dev and use a js library like jQuery. Then you can do something like $('input[name=radioName]:checked').val()

This is exactly why you should use a javascript library.
document.querySelector('input[name=nameOfradio]');
for example is not supported before IE8.
Let the library handle the browser craziness.
In jQuery you can just use $('input[name=radioName]:checked').val() or $("form").serialize() and be done with it.

You can use the class property if your looking for a quick solution. Many elements can have the same class. use the command:
document.getElementsByClass('nameOfradio');
In addition you should use the correct form of getting elements by name which is:
document.getElementsByName('nameOfradio');
You can also use the following code to find the selected radio value as follows:
radioObj=document.getElementsById('nameOfradio');
var radioLength = radioObj.length;
if(radioLength == undefined) {
if(radioObj.checked) {
return radioObj.value;
} else {
return "";
}
}
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";

Related

How to get value for radio button from sql server using ajax and represent to list radio button

I need get value for radio button from sql server using ajax ,php and represent value in form contain radio here code ajax
function getname()
{
var id=$("#idEmploye").val(); // get the id from textbox
$.ajax({
type:"post",
dataType:"json",
data:"id="+id,
url:"page.php", // url of php page where you are writing the query
success:function(json)
{
$("#gender").val(json.gender).prop('checked',true)
}
});
}
code html here
<label >Gender</label>
<input name="gender" id="gender" type="radio" value="Male" >Male</input>
<input name="gender" id="gender" type="radio" value="Female">Female</input>
currently can show value in textbox not in radio button but I need show value in radio button any help
Very Thanks
Try this,
$("input:radio[name='gender'][value='"+ json.gender +"']").attr('checked', true);
or
$("input:radio[name='gender'][value='"+ json.gender +"']").prop('checked', true);
Then each input elements of id should be unique. Please remove the repetitive id . Use name property behalf of id
Basically two html elements should not have same id. So change your HTML like
<label >Gender</label>
<input name="gender" id="Male" type="radio" value="Male" >Male</input>
<input name="gender" id="Female" type="radio" value="Female">Female</input>
The you can set the value with js
var gender = element = document.getElementById(json.gender);
gender.prop('checked');
If you are using an older jquery version (< 1.6)
gender.attr('checked');

Radio button with jQuery and AJAX

I've got the following error when i'm sending the form, to be exact with radio button input.
Here is the HTML Code:
<input name="radio" type="radio" class="raido-btn" id="coral1" value="coral1" />
<label for="coral1">CORAL I</label>
<input name="radio" type="radio" class="raido-btn" id="coral2" value="coral2" />
<label for="coral2">CORAL II</label>
<input name="radio" type="radio" class="raido-btn" id="coral3" value="coral3" />
<label for="coral3">CORAL III</label>
Here is the Javascript code:
if($('#coral1').prop('checked')){
apartamentos = 'Coral 1';
}
else if($('#coral2').prop('checked')){
apartamentos = 'Coral 2';
}
else if($('#coral3').prop('checked')){
apartamentos = 'Coral 3';
}
I don't know how to set the variable "apartamentos" to the radio button which is checked.
It always set the variable apartamentos = 'Coral'
Thanks in advance
JQuery has a few ways to do this. One way I usually do it is by using .is(), for example, $('#coral2').is(':checked'). You could also use apartamentos = $('.raido-btn:checked').val()
What are you attaching that if statement to? I attached it to the clickevent in jsFiddle and and it seems to be working fine. I'm not sure if you want apartamentos to be set to the value of the radio button or the strings that you defined, but it's definitely being updated.
http://jsfiddle.net/FTT5e

jQuery radio button select only one (ID)

I have 2 groups raido buttons, they have different unique IDs, how to make they can be selected only one for each group. Thanks
<group>
<input type="radio" id="u1"/>1
<input type="radio" id="u2"/>2
<input type="radio" id="u3"/>3
</div >
</group>
<group>
<input type="radio" id="T1"/>4
<input type="radio" id="T2"/>5
<input type="radio" id="T3"/>6
</group>
http://jsfiddle.net/pZdWu/
I don't want to change the html, just want to use jQuery to achieve
If you really must use the existing HTML, then I'd suggest amending the HTML via jQuery to simply use the default functions of a radio input:
​$('group').each(
function(i,e){
$(e).find('input:radio').attr('name', 'group' + i);
});​​​​​
JS fiddle demo.
References:
attr().
each().
Give each item in the group a common name using the name attribute.....
<input type="radio" name="group1" id="u1"/>1
<input type="radio" name="group1" id="u2"/>2
<input type="radio" name="group1" id="u3"/>3
Using jQuery, you can use something like this:
http://jsfiddle.net/pZdWu/5/
$(document).ready(function () {
$("input[type=radio]").click(function () {
var $this = $(this);
$this.siblings("input[type=radio]").prop("checked", false);
});
});
But this assumes your HTML structure is exactly as you provided.
If the radio buttons have any kind of wrapping HTML on them, or are grouped inside any way, the use of siblings won't work. You might have to use something like:
http://jsfiddle.net/pZdWu/7/
$(document).ready(function () {
$("input[type=radio]").click(function () {
var $this = $(this);
$this.parents("group:first").find("input[type=radio]").not($this).prop("checked", false);
});
});
And obviously change the use of "group" to whatever you are actually using (I thought I saw you edited your original question to not use <group>).

How to get a radio button index number from a each function in jquery

When using the each() function in jquery for a group of, let's say, 3 radio buttons, how do I retrieve the 3rd button so when it's checked something happens?
Basically how do I choose the element I want to work with from the each() function?
Here is my coding:
HTML:
<form id="orderDefinition" name="orderDefinition">
<fieldset>
<input type="radio" name="radioGroup" /><label for="">radio 1</label>
<input type="radio" name="radioGroup" /><label for="">radio 2</label>
<input type="radio" name="radioGroup" /><label for="">radio 3</label>
</fieldset>
</form>
jQuery:
var radioBtnCollection = $("#orderDefinition input:radio");
$(radioBtnCollection).each(function(){
// From here, I don't know how to get the element
});
Thanks in advance.
You can refer to the element using the this operator:
radioBtnCollection.each(function(){
alert(this.name);
});
Or by using the arguments supplied to the function:
radioBtnCollection.each(function(index, element){
if (index == 2 && element.checked)
alert("3rd element is checked!");
});
If you want to perform any jQuery methods on the element, you will need to wrap it with jQuery. For the first example, $(this), for the second example $(element).
You can just get the third radio button using :eq(2), instead of each:
if ($("#orderDefinition input:radio:eq(2)")[0].checked)
alert("3rd element is checked!");
Use this wrapped as a jQuery object:
$(radioBtnCollection).each(function(){
// this points to the element being iterated
$(this)
});

How can we access the value of a radio button using the DOM?

How can we access the value of a radio button using the DOM?
For eg. we have the radio button as :
<input name="sex" type="radio" value="male">
<input name="sex" type="radio" value="female">
They are inside a form with name form1. When I try
document.getElementByName("sex").value
it returns 'male' always irrespective of the checked value.
Just to "generify" Canavar's very helpful function:
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
... which would now be referenced thusly:
getRadioValue('sex');
Strange that something like this isn't already a part of prototype.js.
Surprised no-one has suggested actually using the Selector API:
document.querySelector('input[name=sex]:checked').value
Browser support is good
If you need the selected one, most frameworks support functionality like this:
//jQuery
$("input[name='sex']:checked").val()
You can get your selected radio's value by this method :
<script>
function getRadioValue()
{
for (var i = 0; i < document.getElementsByName('sex').length; i++)
{
if (document.getElementsByName('sex')[i].checked)
{
return document.getElementsByName('sex')[i].value;
}
}
}
</script>
There are a couple of ways.
1. Put an id on each input
<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">
Then you can use document.getElementById("sex_male")
2. Use something like PrototypeJS (jQuery works too)
Then you can do something like this:
//This loops over all input elements that have a name of "sex"
$$('input[name="sex"]').each( function(elem) {
//Do something
});
Or even this to get at just the "male" radio button:
$$('input[name="sex"][value="male"]').each(function(elem) {
//Do something
});
An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:
for (var i = 0; i < document.form1.sex.length; i++) {
if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
if(list[i].type=='radio' && list[i].checked){
alert(list[i].value);
break;
}
}
If you use document.form1.sex, you are returned an array.
document.form1.sex[0] = first radio button
document.form1.sex[1] = second radio button
To check which is checked you need to loop:
whoChecked(document.form1.sex)
function whoChecked(fieldName) {
for(var x=0;x<fieldName.length;x++) {
if(fieldName[x].checked) {
return fieldname[x].value
}
}
document.getElementByName("sex").value
You mean getElementsByName('sex')[0].value? (There's no getElementByName.)
That will of course always pick the first input element with that name — the one whose value is indeed male. You then check to see if it's selected by using the ‘.checked’ property.
For this simple case you can get away with:
var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';
For the general case you have to loop over each radio input to see which is checked. It would probably be better to get the form object first (putting an id on the form and using document.getElementById is generally better than using the ‘name’-based document.forms collection), and then access form.elements.sex to get the list, in case there are any other elements on the page that have name="sex" attributes (potentially other things than form fields).
function getEleByName(){
if(true==document.getElementsByName('gender')[0].checked){
alert('selected gender is: male');
}
else{
alert('selected gender is: female');
}
}
Loops can achieve the task, as others have shown but it could be simpler than using a loop, which will help performance if desired. Also, it can be portable/modular so it can be used for different radio groups.
Simple Example
function getValue(x) {
alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
A more complex example:
function getValue(x){
alert(x.value);
}
<fieldset>
<legend>Sex</legend>
<label>Male:
<input name="sex" type="radio" value="male" onChange="getValue(this)"/>
</label>
<label>Female:
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
</label>
</fieldset>
<fieldset>
<legend>Age Group</legend>
<label>0-13:
<input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
</label>
<label>13-18:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>18-30:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>30+:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
</fieldset>
document.all.sex[0].checked
document.all.set[1].checked

Categories