Firstly I apologies, I've just starting out with JavaScript
I have a problem with a form. I have two groups of Radio buttons on the form (age and bmi)
Everytime the 'Calculate' button is clicked, I want add the values of each checked Radio button and alert this to the screen.
It works in Chrome, but ALL other browsers give an NAN error.
Can anyone help?
<br>
<input type="radio" name="age" class="myradioButton" value = "1"/>
<input type="radio" name="bmi" class="myradioButton" value = "3"/>
<input type="button" name="Calculate" id="calculate"onclick="calculatehealth()" value="Calculate"/>
<br>
<script>
function calculatehealth() {
var valueAge = document.forms['myForm'].elements["age"].value;
var valueint = parseInt(valueAge);
var valueBmi = document.forms['myForm'].elements["bmi"].value;
var Bmiint = parseInt(valueBmi);
var total = Bmiint + valueint;
alert(total);
}
Demo: http://jsfiddle.net/z4RKx/
HTML
<form id="myForm">
<input type="radio" name="age" class="myradioButton" value="1" />
<input type="radio" name="bmi" class="myradioButton" value="3" />
<input type="button" name="Calculate" value="Calculate" onclick='calculatehealth()' />
</form>
JS
function calculatehealth() {
var valueint = 0;
if (document.forms['myForm'].elements["age"].checked) {
valueint += parseInt(document.forms['myForm'].elements["age"].value);
}
if (document.forms['myForm'].elements["bmi"].checked) {
valueint += parseInt(document.forms['myForm'].elements["bmi"].value);
}
alert(valueint);
}
And if you have many elements this might be a good alternative:
function calculatehealth() {
var valueint = 0;
for(i = 0; i < document.forms['myForm'].elements.length; i++) {
if (document.forms['myForm'].elements[i].checked) {
valueint += parseInt(document.forms['myForm'].elements[i].value);
}
}
alert(valueint);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to disable the checkboxes when a limit of checked checkboxes have reached. I have made a function in JavaScript in which on check of two boxes the other two become disable and the value of the checked boxes comes in id="order2". But this function is not at all working.
<!DOCTYPE html>
<html>
<body>
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
<script>
function myFunction2() {
var coffee = document.querySelectorAll("[name = coffee]"); // To get arrays by Attribute in query selector use [] to get arrays of the same attribute. We can also use ("input[type = checkbox]") to get arrays.
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
txt = txt + coffee[i].value + ", ";
document.getElementById("order2").value = "You ordered a coffee with: " + txt.slice(0, -2);
}
else if (coffee.length === 2) {
coffee[i].setAttribute("style", "pointer-events: none; opacity: 0.5");
document.getElementById("order3").value = "Boxes left uncheck " + i;
}
}
}
</script>
</body>
</html>
Make two loops. First figure out the total number of checkboxes that are checked - this will tell you whether you need to disable unchecked checkboxes. On the second loop, if a checkbox is checked, add its value to an array. Otherwise, the checkbox is unchecked; if at least 2 checkboxes are checked (identified by the previous loop), disable it.
If the user de-selects an option after hitting the limit of 2, also loop through the checkboxes and enable them all.
function myFunction2() {
const checkboxes = [...document.querySelectorAll("[name = coffee]")];
const boxesChecked = checkboxes.reduce((a, b) => a + b.checked, 0);
document.getElementById("order3").value = "Options left to choose:" + (2 - boxesChecked);
let addedCost = 0;
for (const checkbox of checkboxes) checkbox.disabled = false;
for (const checkbox of checkboxes) {
if (checkbox.checked) addedCost += Number(checkbox.value);
else if (boxesChecked === 2) checkbox.disabled = true;
}
document.getElementById("order2").value = "Costs: " + addedCost;
}
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
Try to available mixing HTML with JavaScript using onclick. The proper way is with event listeners, for example:
const myCheckboxes = document.querySelectorAll('input[type=checkbox]');
const myReset = document.querySelector('input[type=reset]');
myCheckboxes.forEach(checkbox => checkbox.addEventListener('click', checkCheckboxes));
myReset.addEventListener('click', resetCheckboxes);
function checkCheckboxes() {
let checked = document.querySelectorAll('input:checked');
if (checked.length >= 2) {
myCheckboxes.forEach(checkbox => checkbox.disabled = true);
}
}
function resetCheckboxes() {
myCheckboxes.forEach(checkbox => checkbox.disabled = false);
}
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" value="100">With cream<br>
<input type="checkbox" name="coffee" value="150">With sugar<br>
<input type="checkbox" name="coffee" value="200">With milk<br>
<input type="checkbox" name="coffee" value="250">With tea<br>
<br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
You can evaluate how many are checked when they are clicked and disable the others. Note: the better way to handle this is to use classes and toggle the class.
'use strict';
document.addEventListener('click', function(e) {
if (e.target.type == 'checkbox')
myFunction2(e);
})
function myFunction2(e) {
const coffee = document.querySelectorAll('[name=coffee]');
const checked = document.querySelectorAll(':checked');
const order2 = document.querySelector('#order2');
const order3 = document.querySelector('#order3');
order2.value = checked.length
? "You ordered a coffee with: " + [...checked].map(cb => cb.value).join(', ')
: ''
if (checked.length === 2 && e.target.checked) {
coffee.forEach(cb => {
if (!cb.checked)
cb.disabled = true
});
order3.value = "Boxes left unchecked: " + (coffee.length - checked.length);
return false;
}
else
coffee.forEach(cb=>cb.disabled=false)
order3.value = "Boxes left unchecked: " + (coffee.length - checked.length);
}
input {
display: block;
}
label {
display: block;
}
label>input {
display: inline-block;
}
<p>How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<label><input type="checkbox" name="coffee" value="100">With cream</label>
<label><input type="checkbox" name="coffee" value="150">With sugar</label>
<label><input type="checkbox" name="coffee" value="200">With milk</label>
<label><input type="checkbox" name="coffee" value="250">With tea</label>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />
This is relatively simple, but I'm missing something. I have 10 checkboxes on a page, in a table in a form. They all have names and id's of add0, add1, add2, etc. I wanted to build a "check/uncheck all" checkbox, but my code doesn't seem to be working. On firefox, using firebug, but it can't seem to follow the script execution.
function checkboxprocess(current)
{
for (i = 0; i < 10; i++)
{
if (current.checked)
{
document.getElementById("add" + i).checked = true;
}
else
{
document.getElementById("add" + i]).checked = false;
}
}
}
Checkbox:
echo "Select All: <input type=\"checkbox\" name=\"add\" id=\"add\" value=1 onChange=\"checkboxprocess(this)\"><br>";
You have extra ] in your code:
document.getElementById("add" + i]).checked = false;
And you don't have to check if is current checked each time in the loop, you can do it easily like this:
function checkboxprocess(current) {
for (i = 0; i < 10; i++) {
document.getElementById("add" + i).checked = current.checked;
// current.checked will return true/false
}
}
<form>
Select All: <input type="checkbox" onChange="checkboxprocess(this)">
<br /> <br />
<input type="checkbox" id="add0">
<input type="checkbox" id="add1">
<input type="checkbox" id="add2">
<input type="checkbox" id="add3">
<input type="checkbox" id="add4">
<input type="checkbox" id="add5">
<input type="checkbox" id="add6">
<input type="checkbox" id="add7">
<input type="checkbox" id="add8">
<input type="checkbox" id="add9">
</form>
i am trying to output value of radio with innerHTML
But i do not succeed in this. What is going wrong?
<script>function changeText(){
var userInputgender = document.getElementByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById('output1').innerHTML = userInputgender;
break;
}
}
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<!-- here comes the output -->
<b id='output1'></b><br />
It's getElementsByName (plural).
function changeText() {
var userInputgender = document.getElementsByName('gender');
for (var i = 0, length = userInputgender.length; i < length; i++) {
if (userInputgender[i].checked) {
document.getElementById('output1').innerHTML = userInputgender[i].value;
break;
}
}
return false;
}
jsFiddle example
And you probably want the value (userInputgender[i].value;) returned to your div.
You could use jquery, it's much better. Look at this example:
HTML:
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<input id="button" type="button" value="Submit" />
<b id='output1'></b>
JS:
$("#button").click(function(){
var $name = $('input[name=gender]:checked').val();
$("#output1").text($name);
});
http://jsfiddle.net/LZWau/1/
<script type="text/javascript">
function changeText()
{
//get your 2 radio buttons
var userInputgender = document.getElementsByName('gender');
//loop on the buttons you found
for(var i=0;i<userInputgender.length;i++)
{
//is the button checked?
if(userInputgender[i].checked)
{
//fill the result element with the button value
document.getElementById('output1').innerHTML = userInputgender[i].value;
}
}
//return false so the form won't commit
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<b id='output1'></b><br />
</script>
http://jsfiddle.net/ayy28/4/
var form = document.forms[0];
var userInputsgender = document.getElementsByName('gender');
form.addEventListener('submit', function(evt){
evt.preventDefault();
for (var i = 0, length = userInputsgender.length; i < length; i++) {
if (userInputsgender[i].checked) {
document.getElementById('output1').innerHTML = userInputsgender[i].value;
break;
}
else {
document.getElementById('output1').innerHTML = 'No gender was selected!';
}
}
});
I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<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>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail