The user should enter five numbers and then after clicking the button another five numbers should be extracted randomly. Based on how many of the numbers guessed match with the random numbers, the program should print six different sentences.
The problem is that I'm stuck, I don't know to to fix it
<!doctype html>
<html lang=it>
<head>
<meta charset="utf-8">
<title>SUPERENALOTTO</title>
<script type="text/javascript">
function reset()
{
document.getElementById("numero1")"
document.getElementById("numero2")"
document.getElementById("numero3")"
document.getElementById("numero4")"
document.getElementById("numero5")"
}
function guessnumbers()
{
var num1,num2,num3,num4,num5,ran1,ran2,ran3,ran4,ran5,N,monete,listanum,ris1,ris2,ris3,ris4,ris5,tot,vincita;
num1=document.getElementById("num1").value;
num2=document.getElementById("num2").value;
num3=document.getElementById("num3").value;
num4=document.getElementById("num4").value;
num5=document.getElementById("num5").value;
monete=document.getElementById("monete").value;
ran1=Math.floor((Math.random()*50));
ran2=Math.floor((Math.random()*49));
ran3=Math.floor((Math.random()*48));
ran4=Math.floor((Math.random()*47));
ran5=Math.floor((Math.random()*46));
N=50;
listanum.apply(null, {length: N}).map(Number.call, Number)
if ((listanum[ran1]==num1)||(listanum[ran2]==num1)||(listanum[ran3]==num1)||(lista[ran4]==num1)||(lista[ran5]==num1))
{
ris1=1;
}
else ris1=0;
if ((listanum[ran1]==num2)||(listanum[ran2]==num2)||(listanum[ran3]==num2)||(lista[ran4]==num2)||(lista[ran5]==num2))
{
ris2=1;
}
else ris2=0;
if ((listanum[ran1]==num3)||(listanum[ran2]==num3)||(listanum[ran3]==num3)||(lista[ran4]==num3)||(lista[ran5]==num3))
{
ris3=1;
}
else ris3=0;
if ((listanum[ran1]==num4)||(listanum[ran2]==num4)||(listanum[ran3]==num4)||(lista[ran4]==num4)||(lista[ran5]==num4))
{
ris4=1;
}
else ris4=0;
if ((listanum[ran1]==num5)||(listanum[ran2]==num5)||(listanum[ran3]==num5)||(lista[ran4]==num5)||(lista[ran5]==num5))
{
ris5=1;
}
else ris5=0;
tot= ris1+ris2+ris3+ris4+ris5
if (tot==5)
{
vincita=(monete*20);
document.getElementById("result").innerHTML=" CINQUINA: Congratulazioni! Vinci "+vincita;
}
if (tot==4)
{
vincita=(monete*10);
document.getElementById("result").innerHTML=" Quaterna: Congratulazioni! Vinci "+vincita;
}
if (tot==3)
{
vincita=(monete*5);
document.getElementById("result").innerHTML=" Terna: Congratulazioni! Vinci "+vincita;
}
if (tot==2)
{
vincita=(monete*2);
document.getElementById("result").innerHTML=" Ambo: Vinci "+vincita;
}
if (tot==1)
{
vincita=(monete*1);
document.getElementById("result").innerHTML=" Un solo numero indovinato: Non perdi e non guadagni ";
}
if (tot==0)
{
vincita=(monete*0);
document.getElementById("result").innerHTML=" Mi dispiace: perdi tutto";
}
}
</script>
</head>
<body>
<div id="titolo">
<h1 id="myDIV">superenalotto</h1>
</div>
<div id="informazione">
</div>
<div id="gioco">
<form>
<p style="text-align:center; font-size:30px ">
<br>
1°Numero <input type="text" id="num1" name="num1">
<br><br>
2°Numero <input type="text" id="num2" name="num2">
<br><br>
3°Numero <input type="text" id="num3" name="num3">
<br><br>
4°Numero <input type="text" id="num4" name="num4">
<br><br>
5°Numero <input type="text" id="num5" name="num5">
<br><br>
Numero pescato1 <input type="text" id="num6" name="num6">
<br><br>
Numero pescato2 <input type="text" id="num7" name="num7">
<br><br>
Numero pescato3 <input type="text" id="num8" name="num8">
<br><br>
Numero pescato4 <input type="text" id="num9" name="num9">
<br><br>
Numero pescato5 <input type="text" id="num10" name="num10">
<br><br>
<h2 style="font-size: 30px; "> Inserisci la tua scommessa</h2>
<br>
<input type="text" id="monete" name="monete">
<br><br>
<input type="button" id="submit" name="Gioca" value="Gioca" onclick="guessnumbers()">
<br><br>
<span id="result" style="font-size:25px; color:red"> </span>
<br>
<br>
<br><br><br>
<input type="submit" id="submit" name="cancella" style=" background- color:red; width:160px; height:50px" value="Ritenta" onclick="reset()">
</form>
</div>
<br><br><br><br><br>
</body>
</html>
var howManyNumbers = 5;
var rememberNumbersArray = []; // We do not repeat numbers
createInput("userInputId", false, "Type number from 1 to 10");
createInput("inputId", true);
// create 6 (howManyNumbers) inputs
function createInput(name, disabled, placeholder){
for(var e = 0; e<howManyNumbers; e++){
lottery.innerHTML+=e+". ";
var input = document.createElement("input");
input.type = "text";
input.id = name+e; // id
if(placeholder){
input.placeholder = placeholder;
}
input.disabled = disabled;
lottery.appendChild(input); // put it into the DOM
lottery.innerHTML+="<BR><BR>"; // gap :D you can use
}
}
function randomNumbers(){
// clear rememberNumbersArray for next lottery :D
rememberNumbersArray = [];
// clear results
results.innerHTML = "";
var count = howManyNumbers;
var numberRnd = 0;
var rndNmb = 0;
var count = 0;
while(count<howManyNumbers){
// ...random
rndNmb = mt_rand(10,1);
if(rememberNumbersArray.indexOf(rndNmb)==-1){
// update input
document.getElementById("inputId"+count).value = rndNmb;
// Remember a random number
rememberNumbersArray.push(rndNmb);
// if count == howManyNumbers, break the loop
count++;
}
}
// check if somebody win
checkWin(count);
}
function checkWin(id){
results.innerHTML = "Winning numbers: <BR>";
for(var e = 0; e<rememberNumbersArray.length; e++){
for(var a = 0; a<howManyNumbers; a++){
if(rememberNumbersArray[e]==document.getElementById("userInputId"+a).value){
results.innerHTML += rememberNumbersArray[e]+"<BR>";
}
}
}
}
function mt_rand(max, min){
return Math.floor(Math.random() * max) + min;
}
Welcome to ITALIA SUPER LOTTO 2017<BR><BR>
<div id="lottery"></div>
<button onclick="randomNumbers();">Generate</button>
<div id="results"></div>
Related
I'm having trouble permuting the values.
<head>
<link rel="stylesheet" type="text/css" href="PinStyle.css"/>
</head>
<body onload="startTime()">
<h1><div id="txt"></div></h1>
<br>
<h1>Pin Algorithm</h1>
<div class="container"
<form action="/action_page.php">
<input type="text" name="message" id="myInput1" value="" maxlength="1">
<input type="text" name="message" id="myInput2" value="" maxlength="1">
<input type="text" name="message" id="myInput3" value="" maxlength="1">
<input type="text" name="message" id="myInput4" value="" maxlength="1"><br><br>
<input id="demo" type="button" value="Permutation" onclick="permute()" /><br/>
</form>
<p id="demo"></p>
These are my textbox inputs
var test1 = "test1";
test1 = document.getElementById("myInput1").value;
var test2 = "test2";
test2 = document.getElementById("myInput2").value;
var test3 = "test3";
test3 = document.getElementById("myInput3").value;
var test4 = "test4";
test4 = document.getElementById("myInput4").value;
var permArr = [],
usedChars = [];
function permute(test1,test2,test3,test4) {
var i, ch;
input=[test1,test2,test3,test4]
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
permute(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr
};
document.write(JSON.stringify(permute(var test1,test2,test3,test4)));
var combinations = permute(input);
document.getElementById("demo").innerHTML = combinations;
</script>
</div>
</body>
This is code to permute values typed into a text-box, I am having trouble getting javascript to read the values, find all combinations, and display the results.
Here it is. I adapted the perm() function, which does the actual permutation, from the accepted answer to this question.
<form action="/action_page.php">
<input type="text" name="message" id="myInput1" value="5" maxlength="1" size="1">
<input type="text" name="message" id="myInput2" value="9" maxlength="1" size="1">
<input type="text" name="message" id="myInput3" value="6" maxlength="1" size="1">
<input type="text" name="message" id="myInput4" value="2" maxlength="1" size="1">
<input type="button" value="Permutation" onclick="permute()" />
</form>
<p id="demo"></p>
<script>
function permute() {
// Create an array with the values of all inputs
const ar = [document.getElementById("myInput1").value,
document.getElementById("myInput2").value,
document.getElementById("myInput3").value,
document.getElementById("myInput4").value];
// Get array of permutations
const permutations = perm(ar);
// Convert array to string before printing it
document.getElementById("demo").innerHTML = JSON.stringify(permutations);
}
function perm(ar) {
let ret = [];
for (let i = 0; i < ar.length; i = i + 1) {
let rest = perm(ar.slice(0, i).concat(ar.slice(i + 1)));
if(rest.length) {
for(let j = 0; j < rest.length; j = j + 1) {
ret.push([ar[i]].concat(rest[j]))
}
} else {
ret.push([ar[i]]);
}
}
return ret;
}
</script>
I want to calculate my input box inner looping and this bellow is what if done please help me to solve this issue
<?php
$jumlah_form = 3;
for($i=1; $i<=$jumlah_form; $i++){
?>
<input type="text" id="txt1" onkeyup="sum1();" /></br>
<?php
}
?>
<input type="text" id="txt2" value= "0" /></br>
<script>
function sum1() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtFirstNumberValue) ;
if (!isNaN(result)) {
document.getElementById('txt2').value = result;
}
}
</script>
Three input boxes are created by looping, I want to calculate three input box, and parse the result into result box whenever user input number
I think you are asking how to write the JavaScript so that it will add up the total of all the input boxes, no matter how many are created by the PHP?
If so then a good way would be to give all the textboxes the same class. Then, the JavaScript can just select all boxes with that class, loop through them and get the total value.
Here's a worked example using 3 textboxes (as if the PHP had generated them this way):
var textboxes = document.querySelectorAll(".sum");
textboxes.forEach(function(box) {
box.addEventListener("keyup", sumAll);
});
function sumAll() {
var total = 0;
textboxes.forEach(function(box) {
var val;
if (box.value == "") val = 0;
else val = parseInt(box.value);
total += val;
});
document.getElementById("total").innerText = total;
}
<input type="number" id="txt1" class="sum" value="0" /><br/>
<input type="number" id="txt2" class="sum" value="0" /><br/>
<input type="number" id="txt3" class="sum" value="0" /><br/>
<br/><br/> Total: <span id="total"></span>
To generate html with php:
$count = 5;
for($i=1;$i <= $count;$i++) {
echo "<input type='number' id='"."txt".i."' /></br>"
}
To calculate sum from inputs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<form onsubmit="submitForm(this); return false;" >
<input type="number" id='text1'>
<input type="number" id='text2'>
<input type="number" id='text3'>
<input type="number" id='text4'>
<input type="number" id='text5'>
<button type="submit" >Calculate</button>
</form>
<div>
<p>Result:</p>
<p id='result'></p>
</div>
<script>
function submitForm(form) {
let toReturn = 0;
const inputs = form.getElementsByTagName("input");
for(let x = 0; x < inputs.length; x++ ) {
toReturn += parseInt(inputs[x].value ? inputs[x].value : 0);
}
document.getElementById('result').innerHTML = toReturn;
return false;
}
</script>
</body>
</html>
I want to improve my Password Generator. I want that the user can choose what the password should include. For example you can choose that the password has letters but no numbers and characters. Can someone say me what i have to do?
here is my javascript and html:-
function randomPassword(length) {
var chars = "abcdefghijklmnopqrstuvwxyz!##$%^&*()-+<>ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var pass = " ";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword(myform.length.value);
}
<form name="myform" method="post" class="form-horizontal">
<div class="form-group " >
<div class="col-sm-10">
<br>
<input class="rowpassword" type="text" name="row_password" size="45s">
<br>
<input class="form-control passwordlength" type="text" name="length" value="8" > password length
<br>
<br>
<input type="checkbox"> Groß - und Kleinbuchstaben
<br>
<input type="checkbox"> numbers
<br>
<input type="checkbox"> specialcharacters
<br>
<br>
<input type="button" class="form-control button" value="Passwort generieren" onClick="generate();" tabindex="2">
</div>
</div>
</form>
Firstly, check for the checked property for the checkboxs.
Then you can decide whether to have more than one pool of characters, or to apply filters which depend on what is checked.
For the former, you can add the appropriate pools together, so something along the lines of
var chars ="";
var letterPool= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialPool="!##$%^&*()-+<>"
var numberPool="1234567890"
if(characterType.checked)
{
chars+=characterTypePool;
}
etc.
If you do this, don't forget to have error handling for when none are selected.
UPDATE:
I've added a snippet (minus error handling) to demonstrate (don't forget to check the boxes!)
function randomPassword(length) {
var chars ="";
var letterPool= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialPool="!##$%^&*()-+<>";
var numberPool="1234567890";
if(document.getElementById('letters').checked)
{
chars+=letterPool;
}
if(document.getElementById('numbers').checked)
{
chars+=numberPool;
}
if(document.getElementById('speChars').checked)
{
chars+=specialPool;
}
var pass = " ";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
pass += chars.charAt(i);
}
return pass;
}
function generate() {
myform.row_password.value = randomPassword(myform.length.value);
}
<form name="myform" method="post" class="form-horizontal">
<div class="form-group " >
<div class="col-sm-10">
<br>
<input class="rowpassword" type="text" name="row_password" size="45s">
<br>
<input class="form-control passwordlength" type="text" name="length" value="8" > password length
<br>
<br>
<input type="checkbox" id='letters'> Groß - und Kleinbuchstaben
<br>
<input type="checkbox" id='numbers'> numbers
<br>
<input type="checkbox" id='speChars'> specialcharacters
<br>
<br>
<input type="button" class="form-control button" value="Passwort generieren" onClick="generate();" tabindex="2">
</div>
</div>
</form>
UPDATE TWO:
To guarantee that there will be at least one of each selected character type, you would need to add code. one way is to choose one at the start, and to add it to a random position in the final password. The following adaptation of the code does so by using an array and splice:
function randomPassword(length) {
var chars ="";
var letterPool= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var specialPool="!##$%^&*()-+<>";
var numberPool="1234567890";
var guaranteed="";
if(document.getElementById('letters').checked)
{
chars+=letterPool;
guaranteed+=letterPool.charAt(Math.floor(Math.random() * letterPool.length));
}
if(document.getElementById('numbers').checked)
{
chars+=numberPool;
guaranteed+=numberPool.charAt(Math.floor(Math.random() * numberPool.length));
}
if(document.getElementById('speChars').checked)
{
chars+=specialPool;
guaranteed+=specialPool.charAt(Math.floor(Math.random() * specialPool.length));
}
var pass =[];
for (var x = 0,len=length-guaranteed.length; x < len; x++) {
var i = Math.floor(Math.random() * chars.length);
pass.push(chars.charAt(i));
}
for(var x = 0,len=guaranteed.length; x < len; x++)
pass.splice(Math.floor(Math.random() * pass.length),0,guaranteed.charAt(x));
pass=pass.join('');
return pass;
}
function generate() {
myform.row_password.value = randomPassword(myform.length.value);
}
I'm just trying to make this check form validation. Like it shouldn't let the form submit unless everything is filled in, then it should do the total only if it works. I'm new to this and I have no idea what is going on, but it is just showing a blue box at the top of my screen by default, and then submitting/accepting regardless of the form being filled out or not.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hands-on Project 6 - Order</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<section>
<article>
<h2>Pizza Order Form</h2>
<div id="errorMessage">
</div>
<form action="results.html" id="orderForm">
<input type="hidden" name="hidden" id="hidden">
<fieldset>
<legend>Delivery Information</legend>
<label for="nameinput">Name</label>
<input type="text" id="nameinput" name="name">
<label for="addrinput">Street Address</label>
<input type="text" id="addrinput" name="address">
<label for="cityinput">City</label>
<input type="text" id="cityinput" name="city">
<label for="emailinput">Email</label>
<input type="email" id="emailinput" name="email">
<label for="phoneinput">Phone</label>
<input type="tel" id="phoneinput" name="phone">
</fieldset>
<fieldset>
<legend>Order</legend>
<p>
<span class="nonLabel">What type of crust:</span>
<br>
<input type="radio" name="crust" id="thin" value="1">
<label for="thin">Thin Crust</label>
<input type="radio" name="crust" id="original" value="0">
<label for="original">Original Crust</label>
<input type="radio" name="crust" id="thick" value="3">
<label for="thick">Deep Dish</label>
</p>
<label for="size" class="nonLabel">What size pizza:</label>
<select id="size" name="size">
<option value=""> </option>
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="XL">Extra Large</option>
</select>
<p>
<span class="nonLabel">What topping(s):</span>
<br>
<input type="checkbox" id="pepperoni" name="toppings" value="Pepperoni">
<label for="pepperoni">Pepperoni</label>
<input type="checkbox" id="sausage" name="toppings" value="Sausage">
<label for="sausage">Sausage</label>
<input type="checkbox" id="bacon" name="toppings" value="Bacon">
<label for="bacon">Bacon</label>
<br>
<input type="checkbox" id="greenpep" name="toppings" value="Green Peppers">
<label for="greenpep">Green Peppers</label>
<input type="checkbox" id="onion" name="toppings" value="Onions">
<label for="onion">Onions</label>
<input type="checkbox" id="xcheese" name="toppings" value="Extra Cheese">
<label for="xcheese">Extra Cheese</label>
</p>
<p>
<label for="instructions" id="instrlabel">Special Instructions:</label>
</p>
<textarea id="instructions" name="instructions" rows="3" cols="60"
placeholder="Special Requests, Delivery Details"></textarea>
</fieldset>
<fieldset id="submitbutton">
<input type="submit" id="submitBtn" value="Add to Cart">
</fieldset>
</form>
</article>
</section>
<script>
document.getElementById("submitBtn ").addEventListener("submit",
validateForm(evt));
</script>
</body>
</html>
JavaScript:
// validate required fields
function validateForm(evt){
if(evt.preventDefault){
evt.preventDefault();
}
else {
evt.returnValue = false;
}
formValidity = true;
validateFormControls();
}
function validateFormControls(){
var inputElements = document.querySelectorAll("fieldset:first-of-type
input");
var errorDiv = document.getElementById("errorMessage");
var crustBoxes = document.getElementsByName("crust");
var fieldsetValidity = true;
var elementCount = inputElements.length;
var currentElement;
try {
for(var i = 0; i < elementCount; i++){
currentElement = inputElements[i];
if(currentElement.value === ""){
currentElement.style.border = "3px solid #0B907A";
currentElement.style.backgroundColor = "#FFC58A";
fieldsetValidity = false;
}
else {
currentElement.style.border = "";
currentElement.style.backgroundColor = "";
}
}
currentElement.querySelectorAll("select")[0];
if (currentElement.selectedIndex === 0){
currentElement.style.border = "3px solid #0B907A";
currentElement.style.backgroundColor = "#FFC58A";
fieldsetValidity = false;
}
else{
currentElement.style.border = "";
currentElement.style.backgroundColor = "";
}
if (!crustBoxes[0].checked && !crustBoxes[1].checked &&
!crustBoxes[2].checked){
crustBoxes[0].style.outline = "3px solid #0B907A";
crustBoxes[1].style.outline = "3px solid #0B907A";
crustBoxes[2].style.outline = "3px solid #0B907A";
}
else {
crustBoxes[0].style.outline = "";
crustBoxes[1].style.outline = "";
crustBoxes[2].style.outline = "";
}
if (fieldsetValidity === false){
throw "Please complete all required fields.";
}
else {
errorDiv.style.display = "none";
errorDiv.innerHTM = "";
}
catch(msg){
errorDiv.style.display = "block";
errorDiv.innerHTML = msg;
formValidity = false;
}
}
}
function orderTotal(){
var itemTotal = 5;
var crusts = document.getElementsByName("crust");
var toppings = document.getElementsByName("goodnight");
var sizes = document.querySelectorAll("select")[0];
if (sizes.selectedIndex > 0) {
itemTotal += ((sizes.selectedIndex * 1) * 2);
}
for (var i=0; i < toppings.length; i++){
if (toppings[i].checked) {
itemTotal += 1;
}
}
for (var i=0; i < crusts.length; i++){
if (crusts[i].checked) {
itemTotal += (crusts[i].value * 1);
}
}
alert ("Your order total is $" + itemTotal);
document.getElementById("hidden").value = itemTotal;
}
Wrong id parameter
document.getElementById("submitButton ").addEventListener("submit", validateForm(evt));
Must be
document.getElementById("submitBtn").addEventListener("submit",validateForm(evt));
I got the following Javascript code that works properly in Mozilla Firefox but it doesn't in Google Chrome. Any ideea why it will do that?
totalBMI in Chrome even if the value is 45(checking all the last buttons will give you the value 45 which is bigger then 26 so the result should be setting the hRisk div to display:-inline instead of display:none, as the function changeCss() does.) it still consider it to be 0, cause it displays the low risk message. In Firefox, it always displays the right answer.
Javascript code :
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
}
changeCSS();
} else if (totalBMI > 16 ) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
}
changeCSS();
} else {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
changeCSS();
}
}
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;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
HTML code:
<script src="jsbmi4.js"></script>
<title>Java</title>
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"> <span class="span1"> How old are you? </span>
<input type="radio" id="age1" name="age" value="0">0-25
<input type="radio" id="age1" name="age" value="5">26-40
<input type="radio" id="age1" name="age" value="8">41-60
<input type="radio" id="age1" name="age" value="10">60+
</label>
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span>
<input type="radio" id="bmi1" name="bmi" value="0">0-25
<input type="radio" id="bmi1" name="bmi" value="0">26-30
<input type="radio" id="bmi1" name="bmi" value="9">31-35
<input type="radio" id="bmi1" name="bmi" value="10">35+
</label>
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes? </span>
<input type="radio" id="fam1" name="fam" value="0">No
<input type="radio" id="fam1" name="fam" value="7">Grandparent
<input type="radio" id="fam1" name="fam" value="15">Sibling
<input type="radio" id="fam1" name="fam" value="15">Parent
</label>
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span>
<input type="radio" id="diet1" name="diet" value="0">Low sugar
<input type="radio" id="diet1" name="diet" value="0">Normal sugar
<input type="radio" id="diet1" name="diet" value="7">Quite high sugar
<input type="radio" id="diet1" name="diet" value="10">High sugar
</label>
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()">
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
Only modification that I had to do is delete the function changeCSS() and just add what was inside in the if statement.
Thanks Fuximus Foe.
JSCode is 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;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
} else if (totalBMI > 16 ) {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
} else {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
}
You have not closed any input tags consider using <input ... /> self closing tags. You have misplaced closing </label> tags.
You shouldn't redeclare a function just to use on the next line.
Not sure, why you're binding to onclick event when you already have the answer, that makes it work only when the user hits the calculate button twice.
After fiddling around with this, removing the the changeCSS functions and just executing their code straight away fixes the problem. This is because in Chrome is grabbing the first definition of the function regardless whether the cursor reaches it or not, thus executing only the first changeCSS function on all three cases; firefox reads the correct definition.
JAVASCRIPT:
function CalculateValue() {
var totalBMI = 0+parseInt(getAgeValue('age'))
+parseInt(getBmiValue('bmi'))
+parseInt(getFamValue('fam'))
+parseInt(getDietValue('diet'));
alert(totalBMI);
if (totalBMI > 26) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'block';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
//}
//}
//changeCSS();
} else if (totalBMI > 16) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'block';
//}
//}
//changeCSS();
} else {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'block';
//}
//}
//changeCSS();
}
}
function getAgeValue() {
for (var i = 0; i < document.getElementsByName('age').length; i++) {
if (document.getElementsByName('age')[i].checked) {
return document.getElementsByName('age')[i].value;
}
}
return 0;
}
function getBmiValue() {
for (var i = 0; i < document.getElementsByName('bmi').length; i++) {
if (document.getElementsByName('bmi')[i].checked) {
return document.getElementsByName('bmi')[i].value;
}
}
return 0;
}
function getFamValue() {
for (var i = 0; i < document.getElementsByName('fam').length; i++) {
if (document.getElementsByName('fam')[i].checked) {
return document.getElementsByName('fam')[i].value;
}
}
return 0;
}
function getDietValue() {
for (var i = 0; i < document.getElementsByName('diet').length; i++) {
if (document.getElementsByName('diet')[i].checked) {
return document.getElementsByName('diet')[i].value;
}
}
return 0;
}
HTML:
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"><span class="span1"> How old are you?</span></label>
<input type="radio" id="age1" name="age" value="0"/>0-25
<input type="radio" id="age1" name="age" value="5"/>26-40
<input type="radio" id="age1" name="age" value="8"/>41-60
<input type="radio" id="age1" name="age" value="10"/>60+
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span></label>
<input type="radio" id="bmi1" name="bmi" value="0"/>0-25
<input type="radio" id="bmi1" name="bmi" value="0"/>26-30
<input type="radio" id="bmi1" name="bmi" value="9"/>31-35
<input type="radio" id="bmi1" name="bmi" value="10"/>35+
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes?</span></label>
<input type="radio" id="fam1" name="fam" value="0"/>No
<input type="radio" id="fam1" name="fam" value="7"/>Grandparent
<input type="radio" id="fam1" name="fam" value="15"/>Sibling
<input type="radio" id="fam1" name="fam" value="15"/>Parent
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span></label>
<input type="radio" id="diet1" name="diet" value="0"/>Low sugar
<input type="radio" id="diet1" name="diet" value="0"/>Normal sugar
<input type="radio" id="diet1" name="diet" value="7"/>Quite high sugar
<input type="radio" id="diet1" name="diet" value="10"/>High sugar
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()"/>
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk" style="display:none;">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
and the JSFiddle: http://jsfiddle.net/kWyx8/