Radio button value selector - javascript

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).

Related

jquery- open and check radio button onclick

I have some radio buttons to filter data on my webpage that are working absolutely fine for me but i am failed to perform check on that radio button...
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=bank-manager'>
<label for="radio1">bank manager</label><br><br>
<input id="radio2" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=ceo'>
<label for="radio2">ceo</label><br><br>
<input id="radio3" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=company-head'>
<label for="radio3">company head</label>
I use jquery to open and perform check on radio button click.
jquery:
$(document).ready(function() {
$('input[type=radio]').click(function() {
window.location=$(this).attr('data-href');
});
// parse the url:
var scat = window.location.search.match(/scat=(\w+)/)[1];
if (typeof scat !== 'undefined') {
// update the correct radio button:
$('input[value="' + scat + '"]').prop("checked", true);
}
});
On using above query if i click on "ceo" radio button, It works for me absolutely fine i.e. it filters content for me and performs check also...
on the other hand if i click on bank manager or company head. It only filters content ..it dosen't perform check...Any help ??
Thanks in advance...
Note: data-href includes url having "-" in bank manager and company head and in label field both bank manager and company head are without "-".
You can put the & (You have incorrect notation used in URL i.e. &&) value as an data attribute as follows,
You have currently as ,
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=bank-manager'>
<label for="radio1">bank manager</label><br><br>
Add data-scat attribute to fetch scat value and also to be able to get clicked based on value,
<input id="radio1" type="radio" name="scat" value="bank-manager" data-scat="bank-manager" data-href='vlist.php?cat=xyz'>
<label for="radio1">bank manager</label><br><br>
And in jQuery you should access it as follows and append in your URL,
$(document).ready(function() {
$('input[type=radio]').click(function() {
window.location=$(this).data('href')+"&scat="+$(this).data('scat');
});
// parse the url:
var hrefLink = window.location.search;
// update the correct radio button:
$('input[value=' + hrefLink.substring(hrefLink.indexOf("scat")+5) + ']').prop("checked", true);
// } Commenting an extra closed bracket
});
Your regex need to be modified to fetch -, also need to change the selector to attribute ends with selector
var search = "?cat=xyz&scat=bank-manager"; //replace with window.location.search
var scat = search.match(/scat=([\w-]+)/);
if (scat && scat[1]) {
// update the correct radio button:
$('input[data-href$=' + scat[1] + ']').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=bank-manager'>
<label for="radio1">bank manager</label>
<br>
<br>
<input id="radio2" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=ceo'>
<label for="radio2">ceo</label>
<br>
<br>
<input id="radio3" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=company-head'>
<label for="radio3">company head</label>
You have not specify the correct value to your radio input tags and you are using value in jQuery selector.Just add the right value to it and it will work fine.
It should be
<input id="radio1" type="radio" name="scat" value="bank-manager" data-href='vlist.php?cat=xyz&&subcat=bank-manager'>
insted of
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&subcat=bank-manager'>
$(document).ready(function() {
$('input[type=radio]').click(function() {
window.location = $(this).attr('data-href');
});
// parse the url:
var search = "vlist.php?cat=xyz&subcat=company-head";
// uncomment this line and comment below one
// var scat = window.location.search.match(/bcat=([\w-]+)/)[1];
var scat = search.match(/bcat=([\w-]+)/)[1];
if (typeof scat !== 'undefined') {
// update the correct radio button:
$('input[value="' + scat + '"]').prop("checked", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="scat" value="bank-manager" data-href='vlist.php?cat=xyz&&subcat=bank-manager'>
<label for="radio1">bank manager</label>
<br>
<br>
<input id="radio2" type="radio" name="scat" value="ceo" data-href='vlist.php?cat=xyz&&subcat=ceo'>
<label for="radio2">ceo</label>
<br>
<br>
<input id="radio3" type="radio" name="scat" value="company-head" data-href='vlist.php?cat=xyz&&subcat=company-head'>
<label for="radio3">company head</label>

Function is not working on radio button onclick

JavaScript function (here f1()) is not getting called on radio button (here id=iprange) onclick event.
HTML
function f1() {
alert('yes');
}
<form role="form">
<div class="box-body">
<label>
<input type="radio" name="optionsRadios" id="fullscan1" value="option1" /> Full Scan
</label>
<!-- "IP Range" is the radio button that should show a "yes" alert. -->
<label>
<input type="radio" name="optionsRadios" id="iprange" value="option2" onclick="f1();" /> IP Range
</label>
From:
<input type="text" id="text1"> To:
<input type="text" id="text2">
<label>
<input type="radio" name="optionsRadios" id="subnet" value="option3" /> Subnet
</label>
<input type="text" id="text3">
<button class="btn btn-danger">Scan</button>
</div>
</form>
#Suresh Kota . At this point its impossible to give an satisfying answer, you'll have to do a step-by-step-investigation. Start with following and post your result here.
<head>
....
<script> // your script tag, I assume it looks like this
$(document).ready(function() {
/* some code */
});
// now include your function as last line outside document ready
function f1() {alert('yes');};
</script>
<!-- Make sure this is the only script tag in your html -->
....
</head>
If that doesn't help, rename your function, e.g. function xxx() {alert('yes');};
and same with onclick-attribute in input-tag: onclick="xxx()".
When having no succes, try directly: onclick="alert('yes')"
If that all not work, there's something inside your document.ready that manipulates the button, and you should post that code.
Try this one:
<input type="radio" name="optionsRadios" onclick="handleClick(this);" value="option1" />
<input type="radio" name="optionsRadios" onclick="handleClick(this);" value="option2" />
...
<script>
function handleClick(myRadio) {
alert('New value: ' + myRadio.value);
}
</script>
<label onclick="red()"><input type="radio" name="colors" id="red">Red</label>
or
<label onclick="red()"><input type="radio" name="colors" id="red"></label>
<label for="red">Red</label>
<script>
function red(){
alert('i am red');
}
</script>
if you want to call onclick function on radio button then you can use like this, it will work for you
Note: we have to call on function on label instead of radio button

how to get only one radio button value in 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>

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.

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