I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}
Related
Currently, you can use the user's final script. This script can modify some previously available variables.
I created a small example in pure javascript I would like to do the same in angular 2+ https://jsfiddle.net/hxs3d0hu/2/
Thank you in advance for your attention
HTML Code
<div class="container">
<form>
<div class="form-group">
<label for="descricao">Nome</label>
<input type="text" id="descricao" name="descricao" class="form-control" />
</div>
<div class="form-group">
<label for="valor">Valor</label>
<input type="text" id="valor" name="valor" value="10" class="form-control" />
</div>
<div class="form-group">
<label for="quantidade">Quantidade</label>
<input type="text" id="quantidade" name="quantidade" value="20" class="form-control" />
</div>
<div class="form-group">
<label for="total">Total</label>
<input type="text" id="total" name="total" class="form-control" />
</div>
<div class="form-group">
<label for="codex">Code</label>
<textarea id="codex" name="codex" rows="10" cols="100" class="form-control">
if (qtde < 15) {
vlr = 10;
}
else
{
vlr = 9;
}
tot = vlr * qtde;
</textarea>
</div>
<button type="button" id="calcular" name="calcular" onclick="calcularx();" class="btn btn-primary">Calcular</button>
</form>
</div>
JavaScript Code
var vlr = 0;
var qtde = 0;
var tot = 0;
function calcularx(){
var valor = document.getElementById("valor");
var quantidade = document.getElementById("quantidade");
var total = document.getElementById("total");
vlr = valor.value;
qtde = quantidade.value;
tot = 0;
tot = qtde * vlr;
total.value = tot;
var codex = document.getElementById("codex").value;
var cst = document.getElementById("customcodescript");
var corpo = "function custom(){ {0} }".replace("{0}", codex);
//cst.innerHTML = corpo;
load_js(cst, corpo);
custom();
valor.value = vlr;
quantidade.value = qtde;
total.value = tot;
console.log(tot);
}
function load_js(cst, corpo)
{
if(cst != null){
cst.remove();
}
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.id = "customcodescript";
script.type= 'text/javascript';
script.innerHTML = corpo;
//script.src= 'source_file.js';
head.appendChild(script);
}
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
Here's a plnkr that would achieve what you're looking for.
http://embed.plnkr.co/w2FVfKlWP72pzXIsfsCU/
You create a function with eval, then call it using the component context. All the function and variable in your component will be available to your textbox code :
The template
Value:
<label>Code:</label>
<textarea [(ngModel)]="code"></textarea> <br>
<button (click)="executeCode(code)">Do it.</button>
The component :
export class HelloWorld {
value = 100;
code = 'this.value = this.value * 100';
executeCode(code){
let fn = eval("(function(){ {0} })".replace("{0}", code));
fn.call(this);
}
}
However, keep in mind that eval is usually evil and that this use case is quite weird. I'm not sure if your user should control the code. Anyhow, that's up to you.
Also, if you want to avoid the "this." in the code text box, you can always use replace on your variable name to add it behind the scene.
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 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/
********************************** EDIT *********************************
HERE IS LINK TO JSFIDDLE TO MAKE IT EASIER TO ANALYSE WHAT I'M TRYING TO RESOLVE
http://jsfiddle.net/Kaleidoscar/ZEd5V/
I have a college assignment to complete which requires me to calculate the price of a hotel and multiply it by the number of days plus any extras to be added to the price of the hotel.
Unfortunately, the code I've provided doesn't work and I'm not sure how I can multiply the hotel price with the holiday duration... If anyone can help me with this problem, I would gladly appreciate the help.
Here is the html code for my assignment:
HTML
Hotels
<div class ="HotelBooking">
<form id="getHotelBooking" onsubmit="return false;">
<ul>
<li><input type="radio" id="Miramar" name="selectedhotel" value="Hotel Miramar" /> Hotel Miramar</li>
<li><input type="radio" id="Jazminas" name="selectedhotel" value="Las Jazminas" /> Las Jazminas</li>
<li><input type="radio" id="Tropicana" name="selectedhotel" value="Tropicana Gardens" /> Tropicana Gardens</li>
</ul>
<input type="button" value="OK" class="buttonstyle" onclick="testHotelImages()" />
<!--INFORMATION ICONS -->
<div class="informationWrap">
<img src="images/information_italic.png" alt="info" class ="infoIcon" />
<p class="imgDescription">Please choose from the selection of Hotels provided. Only 1 hotel can be purchased per hotel booking. To the left hand-side, a hotel description will appear. Only press the OK command once you have confirmed your hotel stay.</p>
</div>
<img id="PricePlaceHolder" src="images/PricePlaceHolder.jpg" alt="Image gallery" height="150" width="150" />
<div class ="Images">
<img id="Hotelplaceholder" src="images/Hotelplaceholder.jpg" alt="Image gallery" height="300" width="615" />
</div>
</form>
</div>
Options
<div class ="HotelBooking">
<form id="getOptionsBooking" onsubmit="return false;">
<ul>
<li><input type="checkbox" id="local" name="check" value="LocalTourOption" /> Tours to Local Interests</li>
<li><input type="checkbox" id="flyDrive" name="check" value="FlyDriveOption" /> Fly-Drive (have a rental car waiting at the airport)</li>
<li><input type="checkbox" id="balcony" name="check" value="BalconyOption" /> Balcony</li>
</ul>
<p><input type="button" class="buttonstyle" value="OK" onclick="ExtraInterest()" /></p>
Duration
<form id="FormNights" action="#">
<p><label for="Nights">Nights:</label>;
<input type="text" size="10" id="Nights" /> </p>
Your Party
<form id="Party" action="#">
<p><label for="Adults">Adults:</label>
<input type="text" size="2" id="AdultsParty" /> </p>
<p><input type="button" class="buttonstyle" value="OK" onclick="PartyDetails()" /></p>
</form>
<h3>Your Holiday Summary</h3>
<div id="TotalCost"> </div>
JAVASCRIPT
var hotel_prices = new Array();
hotel_prices["Hotel Miramar"] = 50;
hotel_prices["Las Jazminas"] = 75;
hotel_prices["Tropicana Gardens"] = 100;
function getHotelPrice() {
var HotelSizePrice = 0;
var theForm = document.forms["getHotelBooking"];
var selectedHotel = theForm.elements["selectedhotel"];
for (var i = 0; i < selectedHotel.length; i++) {
if (selectedHotel[i].checked) {
HotelSizePrice = hotel_prices[selectedHotel[i].value];
break;
}
}
return HotelSizePrice;
function LocalExtra() {
var LocalPrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeLocal = theForm.elements["local"];
if (includeLocal.checked == true) {
LocalPrice = 60;
}
return LocalPrice;
}
function FlyDriveExtra() {
var FlyDrivePrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeFlyDrive = theForm.elements["flyDrive"];
if (includeFlyDrive.checked == true) {
FlyDrivePrice = 45;
}
return FlyDrivePrice;
}
function BalconyExtra() {
var BalconyPrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeBalcony = theForm.elements["balcony"];
if (includeBalcony.checked == true) {
BalconyPrice = 30;
}
return BalconyPrice;
}
function getNights() {
var theForm = document.forms["FormNights"];
var quantity = theForm.elements["Nights"];
var duration = 0;
if (quantity.value != "") {
duration = parseInt(quantity.value);
}
return duration;
}
function getAdults() {
var theForm = document.forms["Party"];
var quantity = theForm.elements["AdultsParty"];
var howmany = 0;
if (quantity.value != "") {
howmany = parseInt(quantity.value);
}
return howmany;
}
function getTotal() {
var HotelPrice = getHotelPrice() + LocalExtra() + FlyDriveExtra() + BalconyExtra() + getNights() + getAdults();
document.getElementById('TotalCost').innerHTML =
"Total Price For Hotel £" + HotelPrice;
}
}
I need some help: I have the following form:
<form id="myForm" method="post" action="?action=agc">
<input type="hidden" name="start_date" value="<?= $_POST['start_date'] ?>" />
<input type="hidden" name="end_date" value="<?= $_POST['end_date'] ?>" />
<input type="hidden" name="c_name" value="<?= $_POST['c_name'] ?>" />
<input type="hidden" name="cluster" value='<?= $abn_cluster[0] ?>' />
<input type="hidden" name="abn" value="abn" />
Add percent <br /><br />
ABN percent<br />
<input type="text" name="poll[option][0][percent]" class="toAdd"> <input type="text" name="poll[option][0][name]" value="<?= $_POST['c_name'] ?>_0_"> <input type="checkbox" class="optionBox" value="True" name="poll[option][0][control_sample]" /><br />
<script>
var optionNumber = 1;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
var newOption2 = document.createElement("input");
var newOption3 = document.createElement("input");
var newLabel = document.createElement("label");
var newContent = document.createTextNode(" ");
var newContent2 = document.createTextNode(" ");
newOption.name = "poll[option]["+optionNumber+"][percent]";
newOption.type = "text";
theForm.appendChild(newOption);
theForm.appendChild(newContent);
newOption2.name = "poll[option]["+optionNumber+"][name]";
newOption2.type = "text";
newOption2.value = "<?= $_POST['c_name'] ?>_"+optionNumber+"_"
theForm.appendChild(newOption2);
theForm.appendChild(newContent2);
newOption3.name = "poll[option]["+optionNumber+"][control_sample]";
newOption3.type = "checkbox";
newOption3.className = "optionBox";
newOption3.value = "True"
theForm.appendChild(newOption3);
theForm.appendChild(document.createElement("br"));
optionNumber++;
}
</script>
</p>
</div>
<div class="modal-footer" id="appendform">
<button type="submit" class="btn btn-primary">Continue</button>
</form>
Now because some of the inputs are generated on request, I have no idea how to check the sum of the(.toAdd). And I basically need to make sure that it's equal to 100 before submitting. What would be a solution to my problem? Thanks.
Try
<form id="myForm" method="post" action="iap_crm_campaign.php?action=abngamecampaign" onsubmit="return validate()">
Then
function validate(){
var sum = 0;
for(var i = 0; i < optionNumber; i++){
sum += parseFloat(document.getElementsByName('poll[option][' + i + '][percent]')[0].value);
}
if( sum == NaN || sum != 100){
alert('Sum of percentage must be 100');
return false;
}
}
Demo: Fiddle
var total = 0;
var toAdds = document.getElementsByClassName("toAdd");
for (var i = 0; i < toAdds.length; i++) {
total += parseInt(toAdds[i].value, 0);
}
if (total == 100) {
// OK
} else {
// not OK
}
Also, your code for adding new options needs to set the class:
newOption.className = "toAdd";
you can use jquery
$(".toAdd").length
or in simple js
var myInputs= document.getElementsByTagName('input');
var noOfInputs =myInputs.length;
well this will give you the count of i/p elements through loop, for summing the values...
var sum;
$(".toAdd").each(function() {
sum=sum+$(this).val();
});