Change radio buttons to check boxes [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have the below form with radio buttons and i want to replace them (the 2 options inc no thanks) with simple check boxes - leaving 3 check boxes.
I can't manage to change the JS to get it working... I've tried tweaking the JS but it stops the ability to either calculate or redirect - which is the main form purpose!
Help!
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input type="radio" name="myRadio1" data-op="0" value="10" onClick="calcNow();" selected />Option A
<input type="radio" name="myRadio1" data-op="1" value="120" onClick="calcNow();" />No thanks<br/>
<input type="radio" name="myRadio2" data-op="0" value="10" onClick="calcNow();" selected />Option B
<input type="radio" name="myRadio2" data-op="1" value="20" onClick="calcNow();" />No thanks<br/>
<input id="myCheckbox" name="myCheckbox" type="checkbox" value="10" onClick="calcNow();" />Otion C<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html","http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]],[["http://mysite.com/page5.html","http://mysite.com/page6.html"],["http://mysite.com/page7.html","http://mysite.com/page8.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox");
var cost1 = getRadioValue("myRadio1");
var cost2 = getRadioValue("myRadio2");
var cost3 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2 + cost3;
document.getElementById("myTotal").value = costTotal;
var op1 = getRadioData("myRadio1", "op");
var op2 = getRadioData("myRadio2", "op");
var op3 = cb.checked ? 1 : 0;
if (op1 != undefined && op2 != undefined && op3 != undefined)
{
return pages[op1][op2][op3];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
// ---- To popup ----
//alert(page);
// ---- To navigate ----
location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>

I suggest for you and I don't your Javascript in you case.
There are two suggest.
You replace on the input radio with two input checkbox.
<input type="checkbox" name="myRadio1" data-op="1" value="on" onClick="calcNow();" />No thanks<br/>
<input type="checkbox" name="myRadio2" data-op="0" value="10" onClick="calcNow();" selected />Option B
This is easy but now it 's difficult.
When the input 's checked, call the function calcNow() but when this is unchecked your can't call the function .
But for the management I suggest that your search on GOOGLE.
For me is better that your add the button that call the function submitForm();
This is a example for checked and unchecked.
EDIT:
I working on your case and there is a solution JSDIFFLE

Related

Check if all radio buttons are clicked in vanilla JavaScript

For exercise, I've created a small HTML-CSS-JavaScript quiz. The quiz itself works but when I tried to edit a way to check if all radio buttons of the quiz are working (and if not, alert a message to the user), it became broken.
Here is the quiz, with the funcion that checks if the radio buttons are clicked:
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
if (document.querySelector('#quiz:not(:has(:radio:checked))').length) {
return alert("At least one group is blank");
} else {
function showScore() {
totalScore = result;
alert(totalScore);
}
}
}
<form id="quiz">
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
<br>
<label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
<br>
<input type="button" onclick="obcpq()" />
<!-- One Button Chcked Per Question -->
</form>
I tried this code after reading of it in this QA session. I also found this session which deals with jQuery and I don't run jQuery on this HTML page.
Why isn't the condition working in my vanilla JavaScript version?
Looking at your HTML code, there's one proportion that can be useful to solve your problem: you want the same number of checked inputs as the number of labels that describe the boxes. When the numbers don't match it's the indicator that not all questions were answered:
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
const labelCount = document.querySelectorAll('#quiz label').length;
const checkedInputsCount = document.querySelectorAll("#quiz :checked").length;
if (labelCount !== checkedInputsCount) {
return alert("At least one group is blank");
} else {
function showScore() {
totalScore = result;
alert(totalScore);
}
}
}
<form id="quiz">
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
<br>
<label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
<br>
<input type="button" onclick="obcpq()" />
<!-- One Button Chcked Per Question -->
</form>
Try to add every question in a separate div then loop through them and check if the group has at least one checked option radio, then use a flag to store the loop result and finally show the right message, like :
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
var groups = document.querySelectorAll('#quiz div');
var all_checked = true;
for (i = 0; i < groups.length; i++) {
if (groups[i].querySelectorAll(':checked').length==0) {
all_checked = false;
}
}
if (!all_checked) {
console.log('Check please all the radios');
} else {
console.log('showScore');
}
}
<form id="quiz">
<div>
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
</div>
<div> <label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
</div>
<input type="button" onclick="obcpq()" value="CHECK"/>
<!-- One Button Chcked Per Question -->
</form>

I need to calculate the value of some checked radio buttons using DOM

My code so far is:
HTML
<input type="radio" name="age" value="0">1-25
<input type="radio" name="age" value="5">26-27
<input type="radio" name="age" value="7">28-29
<input type="radio" name="bmi" value="0">0-25
<input type="radio" name="bmi" value="0">26-30
<input type="radio" name="bmi" value="9">31-35
So I need to get the value of the checked radio buttons and calculate them
Javascript as the first answer that I've got
function CalculateValue(){
//call getAgeValue(), getBmiValue() here and do desired calculations here
}
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
Making use of the vanilla document.querySelector
function doCalculation(ageValue, bmiValue) {
// whatever
return ageValue + bmiValue;
}
function getRadioValue(radio_name) {
return ( // parenthesis to let us do an OR
document.querySelector('input[type="radio"][name="' + radio_name + '"]:checked')
|| // or if none is checked
{} // so we don't get an error
).value;
}
function handlerForButton(e) {
var age = +getRadioValue('age'),
bmi = +getRadioValue('bmi'),
foo = doCalculation(age, bmi);
// do whateverwith foo
console.log(foo);
}
// after elements exist
document.querySelector('input[type="button"][value="Calculate"]')
.addEventListener('click', handlerForButton);
DEMO
You may find it easier to use classes and ids to find your elements rather than seeking them out using their other attributes. This would also improve performance

Getting radio-button value on a loop

I am working with a javascript function which takes the value of some questions using RadioButtons of YES or NO. To get the value of one question(Q1) I do something like this:
for (i=0; i<document.form1.Q1.length; i++){
if(document.form1.Q1[i].checked)
Array[0] = document.form1.Q1[i].value;
}
I have to do this for every question, so the code is getting very long. So I am trying to make a function or a loop in which the name of the question is changing. My only problem is that i dont know how to use a Variable on document.form1.VARIABLE.value. I already tried some ways but didnt work.
Can anyone help me with this?
Thanks a lot!
use
document.forms['form-name']['radio-button-name'].value
and give radio button names like que_1 que_2 so you can change that with i using string concatenation
Here's a loop that will traverse your radio buttons and build an array with the values. In the code and example, it's set for testing three questions (named Q1, Q2, and Q3). When done, the array "aux" contains the list of checked values:
var max = 3;
var aux = new Array();
function getCheckedValue(groupName) {
var radios = document.getElementsByName(groupName);
for (i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
return null;
}
function check() {
for(var i=1;i<=max;i++) {
//console.log(i,getCheckedValue('Q'+i));
aux[i-1] = getCheckedValue('Q'+i);
}
console.log(aux);
}
​
jsFiddle example.
Don't use radio buttons, use checkboxes instead (checked=yes, unchecked=no). Then you can iterate your checkboxes freely, and see what's checked and not. Striked out, OP needs the difference between "yes", "no" and "no answer".
After some extensive coding (my JS is rusty) I came up with the following:
<form name=form1 id=form1 action="index.php">
<p>Question 1</p>
<label><input type="radio" name="Q1" value="yes">Yes</label>
<label><input type="radio" name="Q1" value="no">No</label>
<p>Question 2</p>
<label><input type="radio" name="Q2" value="yes">Yes</label>
<label><input type="radio" name="Q2" value="no">No</label>
<p>Question 3</p>
<label><input type="radio" name="Q3" value="yes">Yes</label>
<label><input type="radio" name="Q3" value="no">No</label>
<button id="go">Go!</button>
</form>
<script type="text/javascript">
check = function (e) {
e.preventDefault(); //Don't submit!
var result = [];
var form = document.getElementById("form1");
for (var i = 1; typeof(form["Q" + i]) != "undefined"; i++) {
for (var j = 0; j < form["Q" + i].length; j++) {
if (form["Q" + i][j].checked) {
result.push(form["Q" + i][j].name + " " + form["Q" + i][j].value);
}
}
}
console.log(result);
}
button = document.getElementById("go");
button.onclick = check;
</script>
Triggered by clicking the "Go!" button.
The point is using the string concatenation of "Q" and i to get to "Q1" "Q2" etc.

JavaScript code for check the value of radio button (jQuery.val(); alternative)

I've two radio buttons to select a type of IVA:
<input type="radio" value="18" checked="true" name="ivacontract"> 18%
<input type="radio" value="16" name="ivacontract"> 16%
And I've one function that will calculate a value depending of the value of the radio button with name "ivacontract". In jQuery I'll use a selector and .val(); to get the value but this application (not coded by me) doesn't use jQuery so I don't know how to do it.
Any help?
Thank you in advance!
function getCheckedValues(objName)
{
var arr = new Array();
arr = document.getElementsByName(objName);
for(var i = 0; i < arr.length; i++)
{
var obj = document.getElementsByName(objName).item(i);
if(obj.checked)
{
alert(obj.value);
}
}
}
getCheckedValues("ivacontract");
Here is a working sample:
http://jsfiddle.net/eJBg9/1/
Try this:
function checkradio(fname,rname)
{
var radios=document[fname].elements[rname];
for(var i=0;i<radios.length;i++)
{
if(radios[i].checked)
return radios[i].value;
}
return false;
}
Where fname is your form name and rname is your radio buttons name that is in your code is ivacontract.
Hope this helps.
Also, here is an example of getting and setting a value for the radio buttons.
http://www.somacon.com/p143.php
<input type="radio" id="radio1" value="18" checked="true" name="ivacontract"> 18%
<input type="radio" id="radio2" value="16" name="ivacontract"> 16%
if (document.getElementById('radio1').checked==true) )
{
/// Your Code ///
}

Undefined value, reading an input

i am geting undefined for ans . why? what is wrong?
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var ansVal = myForm.ans.value;
var qnoVal = myForm.qno.value;
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
<form nam="quiz" id="quiz" >
Yes:
<input type="radio" id="ans" name="ans" value="1" />
<br />No:
<input type="radio" id="ans" name="ans" value="0" />
<input id="qno" type="text" name="qno " value="qqq" />
<input type="button" value="" onClick="submitAnswer(); " />
</form>
Using theForm.inputElement is not standard and can't be guaranteed to work. Instead, you should use document.getElementById, or some other DOM mechanism, to find the input element you want. theForm.elements[name] also works.
You'll also need to fix your element IDs before you can do that - you have two <input type="radio" /> elements with an ID "ans", which is incorrect. IDs must be unique:
<input type="radio" id="ans1" name="ans" value="1" />
<input type="radio" id="ans2" name="ans" value="0" />
<script type="text/javascript">
var ans1 = document.getElementById('ans1');
var ans1value = ans1.value;
</script>
Or, get the radio button group as a single element using elements:
<script type="text/javascript">
var theForm = document.getElementById('quiz');
var ansValue = theForm.elements['ans'].value;
</script>
You have two elements with the same ID, causing a name conflict. They're also the same as the name attribute on the same element, which could cause some confusion down the road.
Try:
var ansVal = myForm.ans.checked;
This will work:
function submitAnswer() {
var myForm = document.getElementById('quiz');
// Set a default value, in case no radio button is selected
var ansVal = 'default value here';
var qnoVal = myForm.qno.value;
// Loop through radio buttons, getting the value of the
// one that is checked (selected).
var radioButtons = myForm.ans;
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
ansVal = radioButtons[i].value;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
this will work too
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var qnoVal = myForm.qno.value;
var ansVal = 'none';
for( i = 0; i < myForm.ans.length; i++ )
{
if( myForm.ans[i].checked == true )
{
ansVal = myForm.ans[i].value;
break;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
This will work
<html>
<form name="form">
Which one is good?<br>
<input type="radio" name="food" value="Spud"
checked="checked"> Spud<br>
<input type="radio" name="food" value="Carrot"> Carrot<br>
<input type="submit" onclick="get_radio_value()">
</form>
<script type="text/javascript>
<!--
function get_radio_value()
{
for (var i=0; i < document.form.food.length; i++)
{
if (document.form.food[i].checked)
{
var rad_val = document.form.food[i].value;
alert(rad_val);
}
}
}
//-->
</script>
</html>

Categories