display the value of all selected radio buttons on a form - javascript

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());
});

Related

Grabbing freetext and radio button values in pure 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);
});

how to uncheck a radio button

I want to uncheck a radiobutton i found a way for doing this but while the radio buttons are inside a form the code won't work this is my script for unchecking a checked radio button
<script type="text/javascript">
var allRadios = document.getElementsByName(1);
var booRadio;
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(booRadio == this){
this.checked = false;
booRadio = null;
}else{
booRadio = this;
}
}
}
</script>
<form name="theForm" target="_blank" action="laravel.php">
<label for="test">test</label>
<input type="radio" id="1" class="radio" name="1" value="1">
<input type="radio" id="2" class="radio" name="1" value="2">
<input type="radio" id="3" class="radio" name="1" value="3">
<input type="radio" id="4" class="radio" name="1" value="4">
</form>
the script works fine when the radio buttons are outside the form tag but it is not working when radio inputs are in the form i am wondering what am i missing here
The problem is the order. You load your javascript before the html is finished.
To solve this, simply place the javascript near the end of the file, just before the closing </body> tag.
If you use jquery, you can also wrap it with $(document).ready(function() { ... }.

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

Radio buttons selected go to URL

I am trying to use the value of the selected radio button to go to a specific URL. Currently the Javascript I am using to do so is choosing the first "id" of the inputs and not using the value of what is actually selected.
HTML
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
Javascript
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + document.getElementById('ns_license').value;
}
</script>
You have multiple ID's that are the same, which is bad! getElementById expects one result, and it gets one by taking the first element which has that ID (ignoring your other 2, as it should). Use the class attribute on similar elements.
<input type="radio" name="ns_license" class="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" class="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" class="ns_license" value="1026" />NeuroSolutions Student
And to get the checked element
var checkedElem = document.querySelector(".ns_license:checked");
And if querySelector is out of the question:
var elems = document.getElementsByClassName("ns_license"),
checkedIndex = 0;
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked)
checkedIndex = i;
}
Your current checked element would be at elems[checkedIndex]
to change a a specific attribute of an element, you can use the
setAttribute()
function of javascript. that should make it work.
While querySelector will work for modern browsers it does not work for IE <=7
If you want you can traverse through the radios by name, then check if the value is checked. If it is then return that value. That is the use of the getRadioValue() function:
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + getRadioValue('ns_license');
}
function getRadioValue(name){
var rads = document.getElementsByName('ns_license');
for(var x=0; x<rads.length;x++){
if(rads[x].checked){
return rads[x].value;
}
}
}
</script>

Print values of selected radio buttons and check-boxes and exclude the submit button

In the script below, how do I get the values of only radio buttons and checkboxes that have been selected and not all (provided a radio button and checkbox were selected).
Right now it gives me the values of all, whether selected or not, and also the submit button (which i dont need).
How do i do this? There'll be more checkboxes and radio buttons, i've used only 2 sets for this question.
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += elem[i].value+"<br>";
}
document.getElementById('lblValues').innerHTML = str;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Add the following test:
if(elem[i].checked)
str += elem[i].value+"<br>";
Also, if you use jQuery, the whole script is even simpler:
function DisplayFormValues(){
$("input:checkbox:checked").add("input:radio:checked")
.each(function(){
$("div#lblValues").append(this.value + "<br>");
});
}

Categories