Grabbing freetext and radio button values in pure javascript - javascript

I have several radio buttons, and the last radio button has a freetext option next to it. I had success getting the values of the radio button OR the freetext, but never both in the same function.
If I had 3 choices, and the 4th choice was another, I would want the function to grab the value without creating a separate Javascript function.
Here was my attempt:
<input type="radio" id = "choice1" name="snooze" value="samplechoice0" onClick='valuechanged();'/> samplechoice0<br>
<input type="radio" id = "choice2" name="snooze" value="samplechoice1" onClick='valuechanged();'/> samplechoice1<br>
<input type="radio" id = "choice3" name="snooze" value="samplechoice2" onClick='valuechanged();'/> samplechoice2 <br>
<input type="radio" id = "choice10" name="snooze" value="Normal Radio" onClick='valuechanged();'/>
<input type="text" id = "choice11" class="tb" name="tb1" placeholder="Enter Other Reason Here" onkeypress='valuechanged();' > <br>
function Submit() {
var items=document.getElementsByClassName('radio');
var selectedItems=" ";
for(var i=0; i<items.length; i++) {
if(items[i].type=='radio' && items[i].checked==true && document.getElementById('choice10').checked==false) {
selectedItems+=items[i].value+"; ";
}
}
if(document.getElementById("choice10").checked == true) {
selectedItems = document.getElementById('choice11').value;
}
alert(selectedItems);
}

Assuming I'm understanding your question, I would pair the two together using a name that matches the radio input's value. For example, if you have a radio input with value="other", just create a textbox with name="otherText"
Then, using an object like { snooze, snoozeText }, allow both values to potentially be undefined, empty string, or whatever else works in your situation. For example:
document.querySelector('.js-snooze-form').addEventListener('submit', e => {
e.preventDefault()
const formElements = e.currentTarget.elements
// Get the snooze value
const snoozeEl = Array.from(formElements.snooze).filter(el => el.checked)[0]
const snooze = snoozeEl && snoozeEl.value
// Get the paired text, if any
const snoozeTextEl = formElements[`${snooze}Text`]
const snoozeText = snoozeTextEl && snoozeTextEl.value
// "Return" the checked snooze value paired with the reason text
console.log({ snooze, snoozeText })
})
form {
display: grid;
gap: 1em;
justify-items: start;
}
<form class="js-snooze-form">
<label><input type="radio" name="snooze" value="0" />Choice 0</label>
<label><input type="radio" name="snooze" value="1" />Choice 1</label>
<label><input type="radio" name="snooze" value="2" />Choice 2</label>
<!-- Define a pairing between other & otherText -->
<div>
<label><input type="radio" name="snooze" value="other" />Other:</label>
<input name="otherText" placeholder="Enter Other Reason Here" />
</div>
<button>Submit</button>
</form>

You can change the ID of the last radio button with free text dynamically by making it equal to the text which is given in by the user.
I also added in following code that when the user gives text input next to the last radio button, the last radio button is automatically checked.
You can then grab the ID of the radio button which is checked.
<form id="radiobuttonForm" name="radiobuttonForm">
<input type="radio" name="choice" id="choice1"> samplechoice0
<br>
<input type="radio" name="choice" id="choice2"> samplechoice1
<br>
<input type="radio" name="choice" id="choice3"> samplechoice2
<br>
<input type="radio" name="choice" id="other" class="other_reason_radio"> samplechoice3
input type="text" id="other_reason_text_input"/>
</form>
var choice;
function getChoice(){
var radios = document.forms["radiobuttonForm"].elements["choice"];
for(var i = 0, max = radios.length-1; i < max; i++) {
radios[i].onclick = function() {
choice=this.id;
console.log('choice: ', choice);
}
}
radios[radios.length-1].onclick = function() {
document.getElementsByClassName("other_reason_radio")[0].id=document.getElementById("other_reason_text_input").value;
choice=this.id;
console.log('choice: ', choice);
}
}
document.getElementById("radiobuttonForm").addEventListener("click", getChoice());
document.getElementById('other_reason_text_input').addEventListener('input', function() {
document.getElementsByClassName("other_reason_radio")[0].checked = true;
document.getElementsByClassName("other_reason_radio")[0].id=document.getElementById("other_reason_text_input").value;
choice=document.getElementById("other_reason_text_input").value;
console.log('choice: ', choice);
});

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>

display the value of all selected radio buttons on a form

I have multiple radio buttons generated in a php loop which looks something like this
while(){
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team1'].' " onclick="return disp()""><span>'.$team1.'</span>
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team2'].' "onclick="return disp()""><span>'.$team2.'</span>
<input type="radio" name="picks'.$x.'" value="draw" onclick="return disp()">
}
What I want to do
Display all selected radio buttons in a div on the bottom of page
My Code
var elmnts = document.getElementById("makePicksForm").elements
var lngth = document.getElementById("makePicksForm").length;
var div = document.getElementById("dispPicks");
for (var x = 0; x < lngth; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML = elmnts[x].value;
}
}
My Problem
Only the value of first selected radio button is displayed in div, other radio buttons are ignored
My Question
Any idea how I can modify my javascript to display the values of ALL selected radio buttons?
Since you've tagged your question with jQuery, here is a jQuery solution. Run the snippet to see it work:
$(document).ready(function () {
$(':radio').change(function (e) {
//clear the div
$('#dispPicks').html('');
//update the div
$(':radio:checked').each(function (ind, ele) {
$('#dispPicks').append($(ele).val() + '<br/>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="foo" value="foo1" />
<input type="radio" name="foo" value="foo2" />
<input type="radio" name="foo" value="foo3" />
<br/>
<input type="radio" name="bar" value="bar1" />
<input type="radio" name="bar" value="bar2" />
<input type="radio" name="bar" value="bar3" />
<br/>
<input type="radio" name="wow" value="wow1" />
<input type="radio" name="wow" value="wow2" />
<input type="radio" name="wow" value="wow3" />
<div id="dispPicks"></div>
You're using lngth in your for loop, but that's defined by getting an element by ID which should only be 1 element. Your loop will only run once that way...
Assuming the element with ID makePicksForm contains all your radio buttons, you need to get the length of the elements:
var elmnts = document.getElementById("makePicksForm").elements;
var div = document.getElementById("dispPicks");
for (var x = 0; x < elmnts.length; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML += elmnts[x].value;
}
}
Also, you need to add the value to the innerHTML property, using +=
as a side note: your PHP loop is creating duplicate ID's, which will result in failures in your javascript code if you need to reference the elements...
Another jQuery-Fiddle
<input type="radio" id="bob" name="boys" value="Bob"><label for="bob">Bob</label><br>
<input type="radio" id="jim" name="boys" value="Jim"><label for="jim">Jim</label><br>
<input type="radio" id="pete" name="boys" value="Pete"><label for="pete">Pete</label><br>
<input type="radio" id="mary" name="girls" value="Mary"><label for="mary">Mary</label><br>
<input type="radio" id="jane" name="girls" value="Jane"><label for="jane">Jane</label><br>
<input type="radio" id="susan" name="girls" value="Susan"><label for="susan">Susan</label>
<h3><span id="boy">?</span> and <span id="girl">?</span></h3>
$("input[name=boys]").click(function () {
$("#boy").text($(this).val());
});
$("input[name=girls]").click(function () {
$("#girl").text($(this).val());
});

default radio button selection using javascript

Here is what i wanted to accomplish. I have 2 sets of radio buttons. Radio button at the same index position in the 2 sets should not be selected at the same time. If a user tries to select, it must show alert and the defaut radio button must be selected.
Here is my html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
[enter link description here][1]
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the JS
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
It works perfectly fine. demo
Now suppose, one of the check box is not selected , say in the second set. If the user selects first radio button from second set, which is already selected in the first, an alert is showed. But the radio button remains selected.
Here is modified html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" onclick="return check();" />
Here is a demo.
NOTE: i can't use jquery since the code is already a part of some legacy application
To me it seems you should arrange the radio buttons in the other way:
<input type="radio" name="col1" value="A1">
<input type="radio" name="col2" value="A2">
<input type="radio" name="col3" value="A3">
<input type="radio" name="col1" value="B1">
<input type="radio" name="col2" value="B2">
<input type="radio" name="col3" value="B3">
That means the user only can select one value in each column without the obtrusive alert or javascript.
This works without jQuery:
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('nope')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Does this fit your needs?
Give value to your radios:
<input type="radio" name="A" checked="checked" value="1" />
<input type="radio" name="A" value="2" />
<br />
<input type="radio" name="B" value="1" />
<input type="radio" name="B" value="2" />
Then you can do as follows:
var radios = document.querySelectorAll('input[type="radio"]');
for(var i=0;i<radios.length;i++){
radios[i].addEventListener('click', check);
}
function check(){
var index= this.value-1;
if(this.name=='A'){
if(document.getElementsByName('B')[index].checked){
alert('already selectedin other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("A")[otherIndex];
other.checked= true;
}
}
else{
if(document.getElementsByName('A')[index].checked){
alert('already selected in other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("B")[otherIndex];
other.checked= true;
}
}
}
check this fiddle

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>

How do I get the value of the checked radio button?

I have this simple script attached to a questionnaire and am having a problem getting the selected answer to show up in a textarea. Here is the script:
function check() {
var complete = 0;
var total = 0;
for (i=0;i<document.form.length;i++)
{
if (document.form.elements[i].checked == true && complete < 10) {
complete++;
total = (total) + (Math.round(document.form.elements[i].value));
}
}
if (complete >= 10) {
document.form.message.value = document.form.question1.value;
}
}
And here is the HTML:
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
I would like the value to be returned, but I am getting undefined. If I alter the line in the script that returns the text to:
document.form.message.value = document.form.question1;
I get [object NodeList]. I know I am missing something so simple but for the life of me I cannot find it.
Also, is it possible I can return the letters A through H along with the value? I know I can replace the value with the letters but need the numbers there for calculations.
My answer is going under the assumption that you would like the <textarea> to be populated with text similar to:
User answered 1 for Question A
User answered 2 for Question F
To get the A or F passed back, I needed to modify your html in the following way:
<input type="radio" value="1" name="question1" onclick="check(this, 'A')"> A<br />
<input type="radio" value="2" name="question1" onclick="check(this, 'B')"> B<br />
<input type="radio" value="3" name="question1" onclick="check(this, 'C')"> C<br />
<input type="radio" value="4" name="question1" onclick="check(this, 'D')"> D<br />
<input type="radio" value="1" name="question2" onclick="check(this, 'E')"> E<br />
<input type="radio" value="2" name="question2" onclick="check(this, 'F')"> F<br />
<input type="radio" value="3" name="question2" onclick="check(this, 'G')"> G<br />
<input type="radio" value="4" name="question2" onclick="check(this, 'H')"> H<br />
<textarea name="message"></textarea>
Otherwise, there's no actual connection between the letter and the radio input.
Anyway, here's what I done did:
I noticed that each group was repeating the same functionality, so I created a single Object Constructor:
var Answer = function () {
this.text = '';
};
this.text will contain the special answer string per group.
Now let's create the two answer group objects:
var answerOne = new Answer();
var answerTwo = new Answer();
Next comes the check() function where we pass the input element as well as it's associated answer character:
var check = function (_input, _question) {
if (_input.name === "question1") {
answerOne.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
if (_input.name === "question2") {
answerTwo.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
document.getElementsByName('message')[0].value = answerOne.text + answerTwo.text;
};
Now, as the user selects an answer, the appropriate answer group's string gets updated accordingly without affecting the other group's answer string.
Here's a jsfiddle with it working: http://jsfiddle.net/smokinjoe/uC76f/13/
Hope that helps!
You are referencing a form element in your script, do you define a form?
The answer seems to be addressed here
Attach event listener through javascript to radio button
Because it's a radio button, you need to loop through all values to find the one that has been selected. Something like this should work:
for (var i=0; i < document.form.question1.length; i++)
{
if (document.form.question1[i].checked)
{
document.form.message.value = document.form.question1[i].value;
}
}
}
Here you go the complete solution.
Couple of things went wrong in your code.
1. The way you get values from radio group. You need to iterate and find out which is checked
2. Setting value to textarea. You need to do getElemenetsByName[x]
<script>
function check() {
var complete = 0;
var total = 0;
var x = document.getElementsByTagName('input');
for(var k=0;k<x.length;k++){
if (x[k].checked && complete < 10) {
complete++;
total = total + Math.round(x[k].value);
}
}
(document.getElementsByName('message')[0]).value = total;
}
</script>
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
Not tested this, and as I don't know the name (or id) of your form(s), or indeed how many forms you have in your document, I have referenced your form by it's id.
function check() {
var complete = 0;
var total = 0;
var formId = 'EnterYourFormId'; // This could be passed as a paramter to the function instead (e.g. "function check(formId) {")
var _from = document.getElementById(formId); // The form could also be referenced by it's index, e.g. document.forms[0]
for (i=0; i < _from.elements.length; i++) {
if (_from.elements[i].type=='checkbox' && _from.elements[i].checked && complete < 10) {
complete++;
total = total + parseInt(_from.elements[i].value);
}
}
if (complete >= 10) {
_form.message.value = _form.question1.value;
}
}

Categories