how to validate all the section by at least choose one option. with my code, it just show the first "please select 1". so how to edit the code to show the all requirement like "pls choose at least one" at beside the section or below the submit button. I'm just a beginner, now learning for JavaScript. You are prefer to done with some code editor, to have a better understand for beginner. Here is my code :
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*454.58;
elec["elec2"] = 200*454.58;
elec["elec3"] = 300*454.58;
elec["elec4"] = 400*454.58;
elec["elec5"] = 500*454.58;
elec["elec6"] = 600*454.58;
elec["elec7"] = 700*454.58;
elec["elec8"] = 800*454.58;
elec["elec9"] = 900*454.58;
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('input[type="checkbox"]');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco;
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vpeople()
{
var cp = document.getElementsByName('selectedperson');
for (var i = 0; i < cp.length; i++)
{
if (cp[i].type == 'radio')
{
if (cp[i].checked) {return true}
}
}
return false;
}
function velec()
{
var ce = document.getElementsByName('electricity');
for (var i = 0; i < ce.length; i++)
{
if (ce[i].type == 'radio')
{
if (ce[i].checked) {return true}
}
}
return false;
}
function vrcyalu()
{
var crcyalu = document.getElementsByName('yesalu');
for (var i = 0; i < crcyalu.length; i++)
{
if (crcyalu[i].type == 'checkbox')
{
if (crcyalu[i].checked) {return true}
}
}
return false;
}
function vrcyplas()
{
var crcyplas = document.getElementsByName('yesalu');
for (var i = 0; i < crcyplas.length; i++)
{
if (crcyplas[i].type == 'checkbox')
{
if (crcyplas[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
if(!vpeople())
{
alert("Please select1");
return false;
}
return true;
if(!vwaste())
{
alert("Please select2");
return false;
}
return true;
if(!velec())
{
alert("Please select3");
return false;
}
return true;
if(!vrcyalu())
{
alert("Please select4");
return false;
}
return true;
if(!vrcyplas())
{
alert("Please select5");
return false;
}
return true;
checkAllRecycles;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5 </label>
<br/><br/>
<label><i class="fa fa-flash"></i>Energy Consumption Per Month</label>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0</option>
<option value="elec1">100</option>
<option value="elec2">200</option>
<option value="elec3">300</option>
<option value="elec4">400</option>
<option value="elec5">500</option>
<option value="elec6">600</option>
<option value="elec7">700</option>
<option value="elec8">800</option>
<option value="elec9">900</option>
</select>
<br/><br/>
<label><i class="fa fa-flash"></i>Recycle </label>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
thx you very much for helping me, stay safe.
hello please check this page :
https://stackoverflow.com/questions/13060313/checking-if-at-least-one-radio-button-has-been-selected-javascript
Related
How to edit the code so that the function calculateTotal can run when the submit button is pressed, and the output is how after the submit button press but not directly show to people by keep adding.
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*(5455/12);
elec["elec2"] = 150*(5455/12);
elec["elec3"] = 200*(5455/12);
elec["elec4"] = 250*(5455/12);
elec["elec5"] = 300*(5455/12);
elec["elec6"] = 350*(5455/12);
elec["elec7"] = 400*(5455/12);
elec["elec8"] = 450*(5455/12);
elec["elec9"] = 500*(5455/12);
elec["elec10"] = 550*(5455/12);
elec["elec11"] = 600*(5455/12);
elec["elec12"] = 650*(5455/12);
elec["elec13"] = 700*(5455/12);
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function waste()
{
var mustwaste=0;
var theForm = document.forms["energyform"];
var waste = theForm.elements["waste"];
if(waste.checked==true)
{
mustwaste=(692/12);
}
return mustwaste;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('.recycle');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + waste() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco.toFixed(2);
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vwaste()
{
var cw = document.getElementsByName('waste');
for (var i = 0; i < cw.length; i++)
{
if (cw[i].type == 'checkbox')
{
if (cw[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
var error = document.getElementById("error")
if (!vwaste())
{
// Changing content and color of content
error.textContent = "Waste must be select"
error.style.color = "red"
return false;
}
return true;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5 </label>
<br/>
<label><i class="fa fa-flash"></i>Waste</label>
<input type="checkbox" id="waste" name='waste' onclick="calculateTotal()" /><span id="error"></span>
<hr><label><i class="fa fa-flash"></i>Energy Consumption Per Month</label></hr>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0kWh</option>
<option value="elec1">100kWh</option>
<option value="elec2">150kWh</option>
<option value="elec3">200kWh</option>
<option value="elec4">250kWh</option>
<option value="elec5">300kWh</option>
<option value="elec6">350kWh (Avg US)</option>
<option value="elec7">400kWh (Avg MY)</option>
<option value="elec8">450kWh</option>
<option value="elec9">500kWh (Avg AS)</option>
<option value="elec10">550kWh</option>
<option value="elec11">600kWh</option>
<option value="elec12">650kWh</option>
<option value="elec13">700kWh</option>
</select>
<hr><label><i class="fa fa-flash"></i>Recycle </label></hr>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' class="recycle" onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' class="recycle" onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
<label>pounds</label>
<div>US Household average is 21,820 lbs per year.</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
Move the call to calculateTotal() to the form's onsubmit instead of doing it in all the onclick.
Also take calls to it out of other functions.
var person = [];
person["person1"] = 1;
person["person2"] = 2;
person["person3"] = 3;
person["person4"] = 4;
person["person5"] = 5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100 * (5455 / 12);
elec["elec2"] = 150 * (5455 / 12);
elec["elec3"] = 200 * (5455 / 12);
elec["elec4"] = 250 * (5455 / 12);
elec["elec5"] = 300 * (5455 / 12);
elec["elec6"] = 350 * (5455 / 12);
elec["elec7"] = 400 * (5455 / 12);
elec["elec8"] = 450 * (5455 / 12);
elec["elec9"] = 500 * (5455 / 12);
elec["elec10"] = 550 * (5455 / 12);
elec["elec11"] = 600 * (5455 / 12);
elec["elec12"] = 650 * (5455 / 12);
elec["elec13"] = 700 * (5455 / 12);
function getNumberperson() {
var numberperson = 0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for (var i = 0; i < selectedPerson.length; i++) {
if (selectedPerson[i].checked) {
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal() {
var electotal = 0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function waste() {
var mustwaste = 0;
var theForm = document.forms["energyform"];
var waste = theForm.elements["waste"];
if (waste.checked == true) {
mustwaste = (692 / 12);
}
return mustwaste;
}
function recyclealu() {
var recyclealu = 0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if (yesalu.checked == true) {
recyclealu = -89.38;
}
return recyclealu;
}
function recycleplas() {
var recycleplas = 0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if (yesplas.checked == true) {
recycleplas = -35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('.recycle');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
}
function calculateTotal() {
var totalco = getNumberperson() * getElectotal() + waste() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco.toFixed(2);
}
//add a function to hide the result on page loading at the start
function hideTotal() {
document.getElementById('totalConsumption').innerHTML = "0";
}
function vwaste() {
var cw = document.getElementsByName('waste');
for (var i = 0; i < cw.length; i++) {
if (cw[i].type == 'checkbox') {
if (cw[i].checked) {
return true
}
}
}
return false;
}
function allvalidate() {
var error = document.getElementById("error")
if (!vwaste()) {
// Changing content and color of content
error.textContent = "Waste must be select"
error.style.color = "red"
return false;
}
return true;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="calculateTotal();return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label>Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1"/>1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" />5 </label>
<br/>
<label><i class="fa fa-flash"></i>Waste</label>
<input type="checkbox" id="waste" name='waste' /><span id="error"></span>
<hr><label><i class="fa fa-flash"></i>Energy Consumption Per Month</label></hr>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' >
<option value="elecuse">0kWh</option>
<option value="elec1">100kWh</option>
<option value="elec2">150kWh</option>
<option value="elec3">200kWh</option>
<option value="elec4">250kWh</option>
<option value="elec5">300kWh</option>
<option value="elec6">350kWh (Avg US)</option>
<option value="elec7">400kWh (Avg MY)</option>
<option value="elec8">450kWh</option>
<option value="elec9">500kWh (Avg AS)</option>
<option value="elec10">550kWh</option>
<option value="elec11">600kWh</option>
<option value="elec12">650kWh</option>
<option value="elec13">700kWh</option>
</select>
<hr><label><i class="fa fa-flash"></i>Recycle </label></hr>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' class="recycle" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' class="recycle" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
<label>pounds</label>
<div>US Household average is 21,820 lbs per year.</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
I tried to build a validation form using JavaScript which handles these errors:
The Name field should not be empty
The phone number field can contain only numbers (exactly 10 numbers)
One option should be selected (radio)
At least one car from checkboxes is selected and at max 3 cars
But the problem with my code is it has not worked in all cases. I mean if I selected submit it shows me the error message just in the name field, not on other fields.
For example here -
here my HTML code
<body>
<div class="MainBackground">
<h1 id="title">Car Company</h1>
</div>
<div class="cars">
<form method="POST" name="form-car" id="form-car">
<p id="decription"> users' request</p>
<div id="name_div">
<label id="lable-name" for="name">Name: </label>
<input id="name" type="text" name="yourName" placeholder="Enter your name"> <br>
<span id="errorname"></span>
</div>
<br> <br>
<label id="lable-Phone" for="Phone">Phone:</label>
<input id="phone" type="text" name="phonefild" placeholder="Enter your Phone Number"> <br>
<span id="errorpass"></span>
<br> <br>
<label id="lable-age" for="Age">Age:</label>
<br>
<input type="radio" name="group1" value="T"> 18-25
<br>
<input type="radio" name="group1" value="A"> 26-35
<br>
<input type="radio" name="group1" value="O"> 35-55
<br>
<input type="radio" name="group1" value="AO"> 36-80
<br>
<input type="radio" name="group1" value="VO"> 80-95
<br>
<span id="radioerorr"></span>
<br> <br>
<label for="check">Choice cars to tested</label>
<br>
<input class="checkbox" type="checkbox" id="option1" name="car1" value="BMW">
<label for="vehicle1">BMW</label><br>
<input class="checkbox" type="checkbox" id="option2" name="car2" value="Ferrari">
<label for="vehicle2">Ferrari</label><br>
<input checkbox="checkbox" type="checkbox" id="option3" name="car3" value="Ford">
<label for="vehicle3">Ford</label><br>
<input class="checkbox" type="checkbox" id="option4" name="car4" value="Audi">
<label for="vehicle4">Audi</label><br>
<input class="checkbox" type="checkbox" id="option5" name="car5" value="Cadillac">
<label for="vehicle5">Cadillac</label><br>
<span id="checkboxerorr"></span>
<br> <br>
<div class="center">
<button onclick="return validition()" id="submit" type="submit" name="button">submit</button>
<button id="reset" type="reset" name="button">reset</button>
</div>
</form>
</div>
And here my javascript code
function validition() {
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
return false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
//return true;
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
return false;
}
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
} else {
document.getElementById('radioerorr').innerHTML = "one option should be selected";
return false
}
}
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
return false
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
}
You are using return statements in your validations, if you return from your 1st validation (name box), the other code blocks will not execute. Use a local boolean to determine your return type and return that at the end of your function, that way, all of your validation code runs. Also, your radio button and checkbox validation logic is flawed, you set an error message on each iteration of the loop if count1 or count2 doesn't meet your conditions. Change it to something like the following:
function validition() {
let valid = true; //local boolean to return at the end of your function
var phoneinpute = document.getElementById('phone').value;
var radios = document.getElementsByTagName('input');
var value;
var inputs = document.getElementsByTagName("input");
var count1 = 0;
var count2 = 0;
var regex = /(5|0)([0-9]{8})$/;
//Name validation
if (document.getElementById('name').value == "") {
document.getElementById('errorname').innerHTML = "name should not be empty";
document.getElementById('name').style.borderColor = "red";
valid = false;
} else if (document.getElementById('name').value != "") {
document.getElementById('errorname').innerHTML = "";
document.getElementById('name').style.borderColor = "green";
}
//Phone number validation
if (regex.test(phoneinpute)) {
document.getElementById('errorpass').innerHTML = "";
document.getElementById('phone').style.borderColor = "green";
} else {
document.getElementById('errorpass').innerHTML = "Invalide phone number";
document.getElementById('phone').style.borderColor = "red";
valid = false;
}
//Radio button validation
for (var i = 0; i < radios.length; i++) {
if (radios[i].type == "radio" && radios[i].checked) {
count1++;
}
if (count1 == 1) {
document.getElementById('radioerorr').innerHTML = "";
break;
}
}
//check to see if you had a checked radio button, if not, add error
//and mark local boolean as false
if(count1 < 1){
document.getElementById('radioerorr').innerHTML = "one option should be selected";
valid = false;
}
//Checkbox validation
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" && inputs[i].checked) {
count2++;
}
}
//Do your checkbox validation after the for loop
if (count2 > 3 || count2 == 0) {
document.getElementById('checkboxerorr').innerHTML = "please choose at least one car and at most 3 cars";
valid = false;
} else {
document.getElementById('checkboxerorr').innerHTML = "";
}
//return your local boolean value
return valid;
}
I am new to javascript..I am facing some problems while trying to implement form submit action onclick using javascript..
The problem is when I implement all the validation checks using if-else conditions ..The function dose not produce any result..
[] 1[]2
I have implemented various validation check and tried to capture all possible form elements with different conditions..But I am failing when I am implementing validation check..otherwise the code works -I cannot figure out what is the problem..
Here is the code:
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNAN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNAN(ag) || ag.parseInt() > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
</head>
<body style="background:pink;">
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>
The first error is at these lines
var nam=document.getElementById("student_name").value;
if(nam.value.length==0 || !(isNAN(nam)) || nam.value.length>20){
nam="Invalid";
}
nam is the value of the input again doing nam.value will throw an error
Secondly isNAN is not a javascript inbuilt function. Case matters while using in build function , it has to be isNaN
Thirdly ag.parseInt() is wrong. Instead it has to be parseInt(ag,10) where 10 is the radix
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNaN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNaN(ag) || parseInt(ag, 10) > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
This might help you
function submitForm()
{
var nam = document.getElementById("student_name").value;
if (!(nam) || nam.length > 20)
{
alert("please Select a valid name");
return false;
}
var ag = document.getElementById("student_age").value;
if (!(ag) || ag > 100)
{
alert("please Select a valid age");
return false;
}
var gender = "";
if(!document.getElementById("g1").checked && !document.getElementById("g2").checked )
{
alert("please Select gender");
return false;
}
else
{
if(document.getElementById("g1").checked)
{
gender = document.getElementById("g1").value;
}
else
{
gender = document.getElementById("g2").value;
}
}
var cty = document.getElementById("city").value;
if (!(cty) || cty=="Default")
{
alert("please Select a city");
return false;
}
var hobbies ="";
if(!document.getElementById("h1").checked && !document.getElementById("h2").checked && !document.getElementById("h3").checked)
{
alert("please Select hobby");
return false;
}
else
{
var inputElements = document.getElementsByName("cbox");
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
var value=" "+ inputElements[i].value;
hobbies +=value;
}
}
}
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body style="background:pink;">
<div id="body">
<form action="#" method="post" onsubmit="return false">
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Default">Select City</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label>
<input type="checkbox" id="h1" name="cbox" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
<input type="submit" value="Submit" onclick="submitForm()">
</form>
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>
I have a group of checkbox that indicates a house spaces, the last checkbox is for the house all space. I want to disable and uncheck other checkboxes when I check "All space" checkbox. what is its javascript code?
<html>
<label class="input-group-addon">
<input type="checkbox" value="1" id="rndr-lobby"
name="rndr-int-options" />
Lobby </label>
<label class="input-group-addon">
<input type="checkbox" value="1.4" id="rndr-room"
name="rndr-int-options" />
Room </label>
<label class="input-group-addon">
<input type="checkbox" value="1.5" id="rndr-living" name="rndr-int-options" />
Living </label>
<label class="input-group-addon">
<input type="checkbox" value="1.6" id="rndr-wc" name="rndr-int-options" />
WC </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-kitchen" name="rndr-int-options" />
Kitchen </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-office" name="rndr-int-options" />
Office </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-saloon" name="rndr-int-options" />
Saloon </label>
<label class="input-group-addon">
<input type="checkbox" value="1.3" id="rndr-all" name="rndr-int-options" onchange="AllCk();"/>
All sapce</label>
</html>
<script>
document.getElementById('rndr-all').onchange = function() {AllCk();};
var AllCk = function () {
var RndrLob = document.getElementById("rndr-lobby"),
RndrRoo = document.getElementById("rndr-room"),
RndrLiv = document.getElementById("rndr-living"),
RndrWc = document.getElementById("rndr-wc"),
RndrKit = document.getElementById("rndr-kitchen"),
RndrOff = document.getElementById("rndr-office"),
RndrSal = document.getElementById("rndr-saloon"),
RndrAll = document.getElementById('rnder-all').checked;
if (RndrAll === true) {
RndrLob.disabled = true; RndrLob.checked = false;
RndrRoo.disabled = true; RndrRoo.checked = false;
RndrLiv.disabled = true; RndrLiv.checked = false;
RndrWc.disabled = true; RndrWc.checked = false;
RndrKit.disabled = true; RndrKit.checked = false;
RndrOff.disabled = true; RndrOff.checked = false;
RndrSal.disabled = true; RndrSal.checked = false;
RndrAll.disabled = true; RndrAll.checked = false;
}
};
</script>
function AllCk() {
if (document.querySelector('#rndr-all').checked) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (inputs[i].id != "rndr-all") {
inputs[i].checked = false;
inputs[i].disabled = true;
}
}
}
} else {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (inputs[i].id != "rndr-all") {
inputs[i].disabled = false;
}
}
}
}
}
// By Jquery, Put it in your AllCk() function
$("input[id='rndr-all']").is(":checked") ?
$("input[name='rndr-int-options']").not("#rndr-all").prop('checked', false).prop('disabled', true) :
$("input[name='rndr-int-options']").not("#rndr-all").prop('disabled', false);
Hope it helps you !
Assuming the fact that All sapce checkbox is the last checkbox in the series, your AllCk() function should be like this:
function AllCk(){
var spaces = document.getElementsByName("rndr-int-options");
for (var i = 0; i < spaces.length - 1; i++) {
if(spaces[i].checked)
spaces[i].checked = false;
}
}
Why this code is not returning the value.When I click Calculate, it does not work.
Comparison is ==
Assignment is =.
You need ageNumerical = 0;
Check out this fiddle.
Here is the snippet.
function getValue() {
var a = patientAge();
var b = patientBmi();
var c = history();
var d = patientDiet();
var totalValue;
totalValue = a + b + c + d;
document.getElementById('message').innerHTML = totalValue;
}
function patientAge() {
var age = document.getElementsByName('ageRange');
var ageBracket;
var ageNumerical;
for (var i = 0; i < age.length; i++) {
if (age[i].checked) {
ageBracket = age[i].value;
}
}
if (ageBracket == "1-25") {
ageNumerical = 0;
} else if (ageBracket == "26-40") {
ageNumerical = 5;
} else if (ageBracket == "41-60") {
ageNumerical = 8;
} else {
ageNumerical = 10;
}
return ageNumerical;
}
function patientBmi() {
var bmi = document.getElementsByName('bmiRange');
var bmiValue;
var bmiNumerical;
for (var i = 0; i < bmi.length; i++) {
if (bmi[i].checked) {
bmiValue = bmi[i].value;
}
}
if (bmiValue == "0-25") {
bmiNumerical = 0;
} else if (bmiValue == "26-30") {
bmiNumerical = 0;
} else if (bmiValue == "31-35") {
bmiNumerical = 9;
} else {
bmiNumerical = 10;
}
return bmiNumerical;
}
function history() {
var patientHistory = document.getElementsByName('familyHistory');
var historyAnswer;
var historyNumerical;
for (var i = 0; i < patientHistory.length; i++) {
if (patientHistory[i].checked) {
historyAnswer = patientHistory[i].value;
}
}
if (historyAnswer == "No") {
historyNumerical = 0;
} else if (historyAnswer == "Grandparent") {
historyNumerical = 7;
} else if (historyAnswer == "Sibling") {
historyNumerical = 15;
} else {
historyNumerical = 15;
}
return historyNumerical;
}
function patientDiet() {
var dietQuestion = document.getElementsByName('dietHabits');
var dietAnswer;
var dietNumerical;
for (var i = 0; i < dietQuestion.length; i++) {
if (dietQuestion[i].checked) {
dietAnswer = dietQuestion[i].value;
}
}
if (dietAnswer == "Low sugar") {
dietNumerical = 0;
} else if (dietAnswer == "Normal sugar") {
dietNumerical = 0;
} else if (dietAnswer == "Quite high sugar") {
dietNumerical = 7;
} else {
dietNumerical = 10;
}
return dietNumerical;
}
<div id="ageQuestion">
<p>How old are you?</p>
<label for="age1">1-25</label>
<input type="radio" name="ageRange" value="1-25" />
<label for="age2">26-40</label>
<input type="radio" name="ageRange" value="26-40" />
<label for="age3">41-60</label>
<input type="radio" name="ageRange" value="41-60" />
<label for="age4">60+</label>
<input type="radio" name="ageRange" value="60+" />
</div>
<div id="bmi">
<p>What is your BMI?</p>
<label for="bmiLevel">0-25</label>
<input type="radio" name="bmiRange" value="0-25" />
<label for="bmiLevel">26-30</label>
<input type="radio" name="bmiRange" value="26-30" />
<label for="bmiLevel">31-35</label>
<input type="radio" name="bmiRange" value="31-35" />
<label for="bmiLevel">35+</label>
<input type="radio" name="bmiRange" value="35+" />
</div>
<div id="family">
<p>Does anybody in your family have Diabetes?</p>
<label for="history">No</label>
<input type="radio" name="familyHistory" value="No" />
<label for="history">Grandparent</label>
<input type="radio" name="familyHistory" value="Grandparent" />
<label for="history">Sibling</label>
<input type="radio" name="familyHistory" value="Sibling" />
<label for="history">Parent</label>
<input type="radio" name="familyHistory" value="Parent" />
</div>
<div id="diet">
<p>How would you describe your diet?</p>
<label for="diet">Low sugar</label>
<input type="radio" name="dietHabits" value="Low sugar" />
<label for="diet">Normal sugar</label>
<input type="radio" name="dietHabits" value="Normal sugar" />
<label for="diet">Quite high sugar</label>
<input type="radio" name="dietHabits" value="Quite high sugar" />
<label for="diet">High sugar</label>
<input type="radio" name="dietHabits" value="High sugar" />
</div>
<button onclick="getValue()">Calculate</button>
<p id="message"></p>
Change == to = when assigning values.
ageNumerical == 0;
to
ageNumerical = 0;