how to get only one radio button value in javascript - javascript

<input type="radio" name="red" value ="red" onclick="myFunction(this.value);"id="chkbx" /> Red<br>
<input type="radio" name="green" value ="green" onclick="myFunction(this.value);"id="chkbx" > green<br>
<input type="radio" name="yellow" value ="yellow " checked onclick="myFunction(this.value);"id="chkbx" > yellow<br>
<input type="radio" name="orange" value ="orange" onclick="myFunction(this.value);"id="chkbx" > orange<br>
<input type="radio" name="blue" value ="blue" onclick="myFunction(this.value);"id="chkbx" > blue<br>
<p id="demo"></p>
button onclick="myfunction(this.value)">My Choice</button>
<br><br>
<p id="demo"></p>
<script>
function myFunction(chkbx)
{
if(chkbx.checked)
{
chkbx.checked = false;
}
else
{
chkbx.checked = true;
}
The Thing is " I want to get the colour from radio button apply to a text in output screen(at a time one radio button would be select).What can i do. Please give some idea. i am new to javascript. I want in javascript only.

.Value will return you the value:
function myFunction(chkbx)
{
if(chkbx.checked)
{
alert(chkbx.value);
}
}

Give all the radio buttons in the group the same name.

Radio buttons allow the user to select only ONE of a predefined set of options. You define groups with the name property (radio buttons with the same name belong to the same group).
So to solve your issue, you can do as belows.
<p><input type="radio" name="color" value ="red"><i>Red</i></p>
<p><input type="radio" name="color" value ="green"><i>Green</i></p>
<p><input type="radio" name="color" value ="yellow" checked><i>Yellow</i></p>
<p><input type="radio" name="color" value ="orange"><i>Orange</i></p>
<p><input type="radio" name="color" value ="blue"><i>Blue</i></p>

Related

Radio button value selector

I am trying to write a form. In the form there will be one set of radio buttons. When I open my html page on my browser, I would like to click one of the buttons and then write its value in a text after I click a submit button.
This is part of the form code:
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
And this is part of my javascript code:
function buildData(){
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
return txtData;
}
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
});
But it is currently not working properly (it won't save the right selection in txt).
How can I fix it? Thanks in advance
UPDATE:
From one of the answers:
function buildData(){
var txtData =
"some text... " + $("[name=tipoBooster]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
}) + "other text...";
return txtData;
}
Here is a simple solution for getting user input when the user changes the checked radio button
$("[name=tb]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
but in your case you need to edit the build function to be like this
function buildData(){
return "type = " + ["custom","block","dark","f1b"][$("[name='tb']:checked").val()];
}
Or if you want more flexible solution you can add labels to your inputs
like this
$("[name='tb']").change(function() {
console.log($(this).parent().text().trim());
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<label><input type="radio" name="tb" value="1" checked="checked" />block</label>
<label><input type="radio" name="tb" value="2" />dark</label>
<label><input type="radio" name="tb" value="3" />f1b</label>
<label><input type="radio" name="tb" value="0" />custom</label>
</dd>
<p></p>
</dl>
</form>
this was for a change event but your build function should be like this then
function buildData() {
return $("[name='tb']:checked").parent().text().trim();
}
Explanation:
$("[name='tb']:checked") gets the checked radio input element
.parent() gets its parent since we need the label to get its text
.text() gets the text of the label
.trim() removes white space before and after the text
Your selector is referencing an id not the name attribute. Try this instead.
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
You could use: $("[name='tb']").val() and just set the corresponding values on the actual radio buttons to block dark etc.
e.g:
<input type="radio" checked="checked" name="tb" value="block"/>
block
<input type="radio" name="tb" value="dark" />
dark
<input type="radio" name="tb" value="f1b" />
f1b
<input type="radio" name="tb" value="custom" />
custom
A # in a jQuery selector is for selecting by id attribute.
What if you change the selector from ($("#tb").is(":checked")... to a name selector.
e.g.
($("input[name*='tb']").is(":checked")
If you just want to get the selected radio button's text. Could you update the html to be.
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<input id="option1" type="radio" checked="checked" name="tb" value="1"/>
<label for="option1">block</label>
...
<p></p>
</dl>
</form>
Then your function can just return the selected text
function buildData(){
return "type = " + $("input[name*='tb']").is(":checked").next("label").text();
}
If you don't want to add labels to the html, then I would try $("input[name*='tb']").is(":checked").next().text();
Maybe sharing a minimum working example link would help, as I am just writing the above from memmory, referencing the documentation (https://api.jquery.com/text/#text).

Javascript radio group by button

How to display an alert msg when all radio button checked to no? I only know check radio by individual only.
//I only know this method
$('#attraction1').change( function(){
if ($(this).is(':checked')) {
alert('Yes');
}
});
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br>
Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" name="individual" value="n" /> No
<br>
Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
In this case you should check something like this
$('#some_button').click( function(){
if ($('input[type="radio"][value="n"]:checked').length == 3) {
alert('Yes');
}
});
You can use a common class for all radio button with no value and a javascript array every method.
This line const radioNames = [...document.getElementsByClassName('no')]; will get all the radio button with no value ... is spread operator and will convert collection so that array method can be used on that collection.
This line item.addEventListener('change', checkIfAllNo) will attach event change to radio button with value no so that it checks the value for all other radio button
Array method every will return true if all the value in that array satisfies the condition.
So in this line radioNames.every(item => {return item.checked;}); if all the radio button with no value is checked then isAllFalse will be true & the alert will be triggered.
const radioNames = [...document.getElementsByClassName('no')];
function checkIfAllNo() {
const isAllFalse = radioNames.every(item => {
return item.checked;
});
if (isAllFalse) {
alert('All False')
}
}
radioNames.forEach((item) => {
item.addEventListener('change', checkIfAllNo)
})
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" class="no" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" class="no" name="individual" value="n" /> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" class="no" name="planBoard" value="n" /> No
In case you have an indeterminate number of inputs you can collect the values for every group and then check if all values match
$("input[type='radio']").change(function() {
// Extract all the radio group names
names = $.unique($('input[type="radio"]').map((v, e) => $(e).attr('name')))
// Collect the value for each group.
// Account for groups that are not selected yet
vals = $.map(names, function(name) {
return $(`input:radio[name="${name}"]:checked`).val() || 'undefined';
})
// Check if collected values match 'n'
console.log(vals.every(v => v == 'n'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" /> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" /> Yes
<input type="radio" id="individual2" name="individual" value="n" checked/> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
#ForeverTwoWheels
Please try this code,To Javascript radio group by button
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Radio Buttons</title>
</head>
<body>
<form>
<input type="radio" name="choice" value="yes"> Yes
<input type="radio" name="choice" value="no"> No
<input type="button" id="btn" value="Show Selected Value">
</form>
<script>
const btn = document.querySelector('#btn');
// handle click button
btn.onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
alert(selectedValue);
};
</script>
</body>
</html>
I hope this information will be usefull for you.
Thank you.

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.

Dynamically adding sets of radio inputs

So I have dynamic form that I create and there could be multiple sets of radio inputs they all do have the same name Release[] but I do not know how to group the properly now if you will add 4 sets of those radio inputs you will be only able to select 1 from all of them
$('a#AddChampion').on('click', function () {
$('div#ChampionInput').append(
'<input type="radio" name="Release[]" value="New">New\
<input type="radio" name="Release[]" value="Rework">Rework\
<input type="radio" name="Release[]" value="None" checked>None\
');
});
Yes if you intend to use the same name only one output can be obtained. If you want to collect them separately you will have to use separate names.
E.g.
For two groups of ReleaseGrp1 and ReleaseGrp2
<input type="radio" name="ReleaseGrp1" value="New">New
<input type="radio" name="ReleaseGrp1" value="Rework">Rework
<input type="radio" name="ReleaseGrp1" value="None" checked>None
<input type="radio" name="ReleaseGrp2" value="New">New
<input type="radio" name="ReleaseGrp2" value="Rework">Rework
<input type="radio" name="ReleaseGrp2" value="None" checked>None

function cal() with radio input

i created a form with cal() but im not able to make it work with radio input.
It worked with select and option, but now the value isnt taken.
here the code
<script>
function cal()
{
var pl=document.form1.template.value;
var resultat=pl;
document.form1.tresultat.value=resultat;
document.formfin.tresultatfin.value = calfin();
}
</script>
<form name="form1">
<label for="Template">Option 1 : Template</label>
<ul>
<li id="template"><label for="logo+texte">Logo et texte</label>
<input type="radio" id="test" name="template" value="500" onclick="cal()"></li>
<li><label for="base">Base</label>
<input type="radio" id="test" name="template" value="800" onclick="cal()"></li>
<li><label for="perso">Sur-Mesure</label>
<input type="radio" id="test" name="template" value="2900" onclick="cal()"></li></ul>
<input type="text" value="0" name="tresultat">
</form>
any idea to get the value in the text input when selected ?
thanks
Radio buttons are weird because there's a list of separate elements instead of just one. The simplest thing to do is to pass the element itself as a parameter:
function cal( button )
{
var pl = button.value;
var resultat=pl;
document.form1.tresultat.value=resultat;
document.formfin.tresultatfin.value = calfin();
}
and then change the radio buttons:
<input type="radio" id="test" name="template" value="800" onclick="cal( this )"></li>
passing this to the function.

Categories