jQuery: how to print out the text label of radio buttons? - javascript

If the code is
<form>
<input type="radio" name="font"> Arial</input><br>
<input type="radio" name="font"> Times New Roman</input><br>
<input type="radio" name="font"> Monaco</input><br>
</form>
<script>
$('form input').each(function(i, e) {
alert($(this).text())
})
</script>
It shows 3 empty strings. How can it show the 3 names of fonts?
try it at: http://jsfiddle.net/bKhsp/3/

You can't have text inside an <input> tag - it's invalid HTML even though the browser will try to render it, if you want that you should use a <label> wrapper (which keeps the text clickable as well) like this:
<form>
<label><input type="radio" name="font" value="Arial"> Arial</label><br>
<label><input type="radio" name="font" value="Times New Roman"> Times New Roman</label><br>
<label><input type="radio" name="font" value="Monaco"> Monaco</label><br>
</form>
With a loop to match:
$('form input').each(function(i, e) {
alert($(this).parent().text()); //for the label text
alert($(this).val()); //for the input value
});
You can view the updated/working fiddle here. For postback reasons, you probably want a value on the inputs as well, so a value for font gets sent.

Inputs never have end tags, meaning to be correct, you'd have to have the following:
<form>
<input type="radio" name="font" /> Arial<br />
<input type="radio" name="font" /> Times New Roman<br />
<input type="radio" name="font" /> Monaco<br />
</form>
From there, you can take measures to tie the text with its respective radio button:
<form>
<input type="radio" name="font" id="fontArial"/><label for="fontArial">Arial</label><br />
<input type="radio" name="font" id="fontTimes"/><label for="fontTimes">Times New Roman</label><br />
<input type="radio" name="font" id="fontMonaco"/><label for="fontMonaco">Monaco</label><br />
</form>
<script type="text/javascript">
$('form label').each(function(i, e) {
alert($(this).text());
})
</script>
For grabbing the respective radio button from the label, simply take the for attribute for a selector id (for example this takes the value of a label's respective radio button):
$('#' + $(this).attr('for')).val();

The input element doesn't have a closing tag. Use a label around the radio button and text, then the text is clickable as it should be:
<form>
<label><input type="radio" name="font"/><span>Arial</span></label><br>
<label><input type="radio" name="font"/><span>Times New Roman</span></label><br>
<label><input type="radio" name="font"/><span>Monaco</span></label><br>
</form>
Putting the text in a span is a good idea, then you can target it separately so that you can style it with CSS.
Use the next function to reach the text from the input:
$('form input').each(function(i, e) {
alert($(this).next().text())
});

You should use a <label> element and specify the id of the input element in its for attribute, that way when you click on the text it will check the radio input for you. As Nick Craver mentioned, you can't have text nodes inside an input element.
You can use nextSibling to get the text node following an element, then access its nodeValue property for the text:
$('form input').each(function(i, e) {
alert(this.nextSibling.nodeValue);
});
This should also be more efficient than solutions that wrap this with jQuery. You can also use this.value to get the value without wrapping and calling .val().
Updated fiddle at http://jsfiddle.net/AndyE/bKhsp/6/.

The HTML markup is incorrect. Each option needs a value:
<form>
<input type="radio" name="font" value="Arial"> Arial <br>
<input type="radio" name="font" value="Times New Roman"> Times New Roman<br>
<input type="radio" name="font" value="Monaco"> Monaco<br>
</form>
Your jQuery can then look something like this (from memory):
$('form input').each(function(i, e) {
alert($(this).val());
})

Related

Make check-boxes becoming one group of radio button

I cannot make the input name same or value same. The second and third inputs come from a loop using c# razor. I have 2 sets of radio inputs first one is one set and second and third are another set. Because the second and third have the same name, checking one makes the other unchecked. I want the same for all of them together so it would be like I have one set of 3 radio buttons. Like I said above I am not able to make the name or value same due to back-end data display issue. Here is my attempt below.
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>
<script>
$(document).ready(function () {
if ($('#dcenter-listradio').prop("checked", true)) {
$('#dcenter-allradio').prop("checked", false);
}
if ($('#dcenter-allradio').prop("checked", true)) {
$('#dcenter-listradio').prop("checked", false);
}
});
</script>
If you can give them all the same class, then you can just use jQuery to detect when a change has occurred and then uncheck other items in the same class.
$(document).ready(function() {
var selector = ".groupTogether";
// or if you can't give same class, you could use "#unrelatedRadio, input[name='related']"
$(selector).change(function()
{
if(this.checked)
{
$(selector).not(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="unrelatedRadio" name="unrelated" type="radio" class="groupTogether">unrelated</input>
<input id="relatedA" name="related" type="radio" class="groupTogether">Related A</input>
<input id="relatedB" name="related" type="radio" class="groupTogether">Related B</input>
Or, if you can't give them the same class, just replace the selector with something that selects both sets (in my example, "#unrelatedRadio, input[name='related']")
let radios = document.querySelectorAll("input");
for (let i of radios){
i.name="same"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>

How to set a default radio button with a value?

General issue: I cannot set a default radio button in my radio groups unless I remove the value attribute from the inputs.
Specifics: Each input has a value that is needed as it is being used by angular in other places in the app. So, I need to know how to set an input to default checked while retaining the values on the inputs. It has the same behavior if I try to add checked with jQuery instead of in HTML.
I have looked at several related questions including here. The specific issue is I need to have values and be able to set one input to checked as a default. The first input is set to checked, but it does not actually work unless I remove the value from that input.
Here is the HTML:
<div class="radio">
<label>
<input type="radio" ng-model="optionsRadios" id="new" value="new" checked>
New
</label>
<label>
<input type="radio" ng-model="optionsRadios" id="used" value="used">
Used
</label>
<label >
<input type="radio" ng-model="optionsRadios" id="broken" value="broken">
Broken
</label>
</div>
You have to use ng-checked="true" instead of checked
<input type="radio" ng-model="optionsRadios" id="new" value="new" ng-checked="true">
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">
<p>My cars:</p>
<input type="radio" ng-model="all" value="Volvo" ng-checked="true">Volvo<br>
<input type="radio" ng-model="all" value="Ford">Ford<br>
<input type="radio" ng-model="all" value="Mercedes">Mercedes
</body>
</html>
If you have a group of radio button and you want to set radio button checked based on model, then radio button which has same
value and ng-model is checked automatically.
<input type="radio"
ng-model="optionsRadio" value="1" >
<input type="radio"
ng-model="optionsRadio" value="2" >
<input type="radio"
ng-model="optionsRadio" value="3" >
If the value of optionsRadio is "2" then second radio button will be selected automatically.
In Your Case:
When u r initiating the controller all u have to do is to assign a value to your model to keep atleast one radio button selected.
Controller part:
$scope.optionsRadio = "new";
Form part:
<input type="radio" ng-model="optionsRadio" value="new" >
<input type="radio" ng-model="optionsRadio" value="used" >
<input type="radio" ng-model="optionsRadio" value="broken" >
First radio button will be selected automatically.
Note:
If value doesn't work u can use ng-value.

on button click show Radio button value is not working when radio value is changed

I am using following on button click inline javascript to show Radio button value. But it is always showing English even if i change the value
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="English" checked="checked">English
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="Tamil">Tamil
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="Hindi">Hindi</div><br>
<input type="button" class="button5" value="Continue" onclick="alert(document.getElementById('LanguageSelect').value);" />
my requirement is, need to show which radio is selected !
Please change the IDs of the element, and then depending on the value, show an element.
Otherwise, DOM cannot do that on itself.
Solution
Remove the id="LanguageSelect" from the HTML, because even if some other is checked, the current element will still have the id property. Here is the example of your code:
Here is the fiddle where I tested your code: http://jsfiddle.net/afzaal_ahmad_zeeshan/q25ba/
So, once you remove that, you'll get the problem fixed.
When you're selecting the value, it will look up for the first element, it will have the value of English, and will alert!
You can either use jQuery or check for the checkness of the elements:
jQuery
$('input[type=radio]:checked').val(); // check for the checked radio
This is easy and simple! I would recommend you this.
However, if you want to get the value of the radio buttons using JavaScript, try this:
JavaScript
/* this event to get triggered on click */
function checkCheckness () {
var radioButton = document.getElementsByName("LanguageSelect");
/* always remember, name should be similar, ID MUST NEVER be similar
* using similar ID among different elements is illegal in HTML */
if(radioButton[0].checked) {
alert(radioButton[0].value);
}
/* add some else statements */
}
If you have only three options, the following solution would be reasonable:
<input type="radio" name="LanguageSelect" id="LanguageSelect1" value="English" checked="checked">English
<input type="radio" name="LanguageSelect" id="LanguageSelect2" value="Tamil">Tamil
<input type="radio" name="LanguageSelect" id="LanguageSelect3" value="Hindi">Hindi</div><br>
<input type="button" class="button5" value="Continue" onclick="alertValue()" />
and then in a script define the alertValue function.
alertValue = function(){
var language1 = document.getElementById('LanguageSelect1');
var language2 = document.getElementById('LanguageSelect2');
var language3 = document.getElementById('LanguageSelect3');
if(language1.checked)
alert(language1.value);
if(language2.checked)
alert(language2.value);
if(language3.checked)
alert(language3.value);
}
Check this one please Fiddle. I have tested there this solution.
If you don't have problem on selecting the elements with another way, then another approach would be the following:
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="English" checked="checked">English
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="Tamil">Tamil
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="Hindi">Hindi</div><br>
<input type="button" class="button5" value="Continue" onclick="alertValue()" />
and the corresponding js function:
alertValue = function(){
var radios = document.getElementsByTagName("input");
for (var i=0;i<radios.length;i++)
if (radios[i].checked)
alert(radios[i].value);
}
Check this one please FiddleV2. I have tested there this solution.
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="English" checked="checked">English
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="Tamil">Tamil
<input type="radio" name="LanguageSelect" id="LanguageSelect" value="Hindi">Hindi</div><br>
<input type="button" class="button5" value="Continue" onclick="clickable()" />
function clickable(){
var val=document.querySelector('input[name="LanguageSelect"]:checked').value;
alert(val);
}
i did it myself...
onclick='if(document.getElementById(\'LanguageSelect1\').checked==true)
{alert(document.getElementById(\'LanguageSelect1\').value);}
if(document.getElementById(\'LanguageSelect2\').checked==true)
{alert(document.getElementById(\'LanguageSelect2\').value);}
if((document.getElementById(\'LanguageSelect3\').checked==true)
{alert(document.getElementById(\'LanguageSelect3\').value);}'

Not able to get the value of Radio Button

<input type="radio" name="animal" id="cat" value="Cat" />
<label for="cat">Cat</label>
<input type="radio" name="animal" id="radio-choice-2" value="choice-2"/>
<label for="radio-choice-2">Dog</label>
<input type="radio" name="animal" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="animal" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
<input type="button" value="Get Radio Button Value" onclick="getValue();"
I want to get the value of selected Radio Button on click of button I had written the code
function getValue () {
alert("Value is :"+$('input[name=animal]:checked').val());
}
But its not working and getting Undefined
Update:
I have used js of Jquery and jquerymobile
for jquery its for fine but as i am using it for mobile app so i need both the js library so in second case it didnot work.
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
[Solved]
Hi I think you are getting the value without checking any radio button.
Load your page then select any one of radio button and then call getValue function
Alternatively you can put any radio button selected by default.
e.g.
replace first radio button with
<input type="radio" name="animal" id="cat" value="Cat" checked="true"/>
<label for="cat">Cat</label>
Try this
$("#myform input[type='radio']:checked").val();
OR
var myRadio = $('input[name=myRadio]');
//Use the filter() function, not find(). (find() is for locating child elements, whereas //filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(':checked').val();

Find name of the radio button that is checked

My page has about 25 radio button groups. When a radio button is selected in a group, I want to perform an action Specific to that group, and so need the NAME attrib of the radio group.
Take this HTML for example :
<div id="stackExchange">
<input type="radio" name="sofu_group" value="Stack Overflow">
<input type="radio" name="sofu_group" value="Meta Stack Overflow">
<input type="radio" name="sofu_group" value="Server Fault">
<input type="radio" name="sofu_group" value="Super User">
</div>
<!-- In no particular order - don't want to start a flame war ;) -->
If you wanted to deduce what group the clicked radio button belongs to you could use something like this :
// jQuery ver 1.7+
$("#stackExchange input:radio").on('click',function(){
var groupName = $(this).attr('name');
var groupElements = $(this).parent().find(":radio[name='"+groupName+"']");
});
Lets see whats going on here :
$("#stackExchange input:radio") - this selector will find us all of the input radio elements that are decendants of the #stackExchange element using the :radio selector. (Link to docs).
$(this).attr('name') - here is where we extract the name attribute of the selected radio element. (In our example - this becomes sofu_group).
$(this).parent() - In this case the variable $(this) refers to the radio element that was clicked - so we are selecting its parent - the #stackExchange element.
parent().find(":radio[name='"+groupName+"']") - this line will find all of the radio buttons held within the element that have a name attribute set to 'sofu_group'.
In the example - the variable $(this) refers to the radio element that was clicked.
This might give you some hint
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.cgi" method="POST">
<div align="center"><br>
<input type="radio" name="group1" value="Milk"> Milk<br>
<input type="radio" name="group1" value="Butter" checked> Butter<br>
<input type="radio" name="group1" value="Cheese"> Cheese
<hr>
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
<input type="radio" name="group2" value="Wine" checked> Wine<br>
</div>
</form>
</body>
</html>
call document.getElementsByName("group1").items(0).<propertyname>or<function>

Categories