i have something like creating order that contain: order-details and order-products
when i click on Create Row the specified data : name, lprice, count, price will add to the table row, include row number
My goal is to define row number on 0 startnig, like these:
<input name="product[0][product_id]" id="product_id" style="display:none" value="25">
<input name="product[0][lprice]" id="lprice" style="display:none" value="25">
the final goal is to get these values with php and then save them in sql
Your suggestions for editing the question will be appreciated
var sp = document.getElementById('product_id');
var lp = document.getElementById('lprice');
var count = document.getElementById('count');
var fp = document.getElementById('price');
var pt = document.getElementById('paytype');
var wrapper=document.getElementById('wrapper');
wrapper.onchange = function(){
var selected = sp.options[sp.selectedIndex];
var selected_type = pt.options[pt.selectedIndex].value;
if (selected_type === "1"){
lp.value = selected.getAttribute('data-fprice');
}
if (selected_type === "2"){
lp.value = selected.getAttribute('data-fpricec');
}
if (selected_type === "3"){
lp.value = selected.getAttribute('data-price');
}
if (selected_type === "4"){
lp.value = selected.getAttribute('data-pricec');
}
fp.value = "";
fp.value = lp.value * count.value;
};
wrapper.onchange();
$(function() {
function numberRows($t) {
var c = 0;
$t.find("tr").each(function(ind, el) {
var number = ++c;
$(el).find("td:eq(0)").html(number + ".");
});
}
$("#add-service-button").click(function(e) {
var product = document.getElementById('product_id');
var selected = product.options[sp.selectedIndex];
product = selected.getAttribute('data-name');
var product_id = $("#product_id").val();
var lprice = $("#lprice").val();
var count = $("#count").val();
var price = $("#price").val();
$product_id = $("<input>").attr({name: 'product['+ 'number' + '][product_id]', id: 'product_id', style:'display:none', value: product_id});
$lprice = $("<input>").attr({name: 'product['+ 'number' + '][lprice]', id: 'lprice', style:'display:none', value: lprice});
$count = $("<input>").attr({name: 'product['+ 'number' + '][count]', id: 'count', style:'display:none', value: count});
$price = $("<input>").attr({name: 'product['+ 'number' + '][price]', id: 'price', style:'display:none', value: price});
e.preventDefault();
var $row = $("<tr>");
$row.append($("<td>"));
$row.append($("<td>").html(product).append($product_id));
$row.append($("<td>").html(lprice).append($lprice));
$row.append($("<td>").html(count).append($count));
$row.append($("<td>").html(price).append($price));
$row.append($("<td>").html("<a class='del-service text-danger' href='#' title='Click to remove this entry'>X</a>"));
$row.appendTo($("#service-table tbody"));
numberRows($("#service-table"));
});
$("#form-entry form").submit(function(e) {
e.preventDefault();
$("#add-service-button").trigger("click");
});
$("#service-table").on("click", ".del-service", function(e) {
e.preventDefault();
var $row = $(this).parent().parent();
var retResult = confirm("Are you sure?");
if (retResult) {
$row.remove();
numberRows($("#service-table"));
}
});
});
.form-entry input, .form-entry select {
border: 1px solid #ccc;
padding: 10px;
padding-left: 1em;
}
.form-entry button {
border: 0;
background-color: #5AD0A1;
color: #fff;
cursor: pointer;
padding: .6em 1.25em;
}
.table-wrapper {
font-family: Arial, sans-serif;
}
.table-wrapper table td {
border-bottom: 1px dashed #ccc;
padding: 1em .2em;
}
.table-wrapper table tr:last-child td {
border-bottom: 0;
}
.table-wrapper table td:first-child {
color: #ccc;
width: 2em;
}
.table-wrapper table td:last-child a {
color: #F00;
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<form>
<div class="form-entry">
<select name="paytype" id="paytype">
<option style="display:none">Pay Type:</option>
<option value="1" data-price="">First sell, Cash</option>
<option value="2" data-price="">First sell, Check</option>
<option value="3" data-price="">Cash</option>
<option value="4" data-price="">Check</option>
</select>
<select name="product_id" id="product_id">
<option style="display:none">Select Product</option>
<option value="1" data-fprice="10" data-fpricec="12" data-price="15" data-pricec="17" data-name="Bag">Bag</option>
<option value="2" data-fprice="20" data-fpricec="22" data-price="25" data-pricec="27" data-name="Hat">Hat</option>
<option value="3" data-fprice="30" data-fpricec="33" data-price="35" data-pricec="37" data-name="Watch">Watch</option>
</select>
<input name="lprice" id="lprice" tabindex="1" value="" placeholder="Price" readonly="" type="currency">
<input name="count" id="count" tabindex="1" value="" placeholder="Count" type="number">
<input name="price" id="price" tabindex="1" value="" readonly="" placeholder="Full Price" type="currency">
<button type="submit" id="add-service-button">Create Row</button>
</div>
<div class="table-wrapper">
<table id="service-table" width="100%">
<tbody>
</tbody>
</table>
</div>
</form>
</div>
You can post multiple inputs with the same name as an array, I suggest using something as
<select name="product_id[]" id="product_id_1">
<input name="lprice[]" id="lprice_1" tabindex="1" value="" placeholder="Price" readonly="" type="currency">
<input name="count[]" id="count_1" tabindex="1" value="" placeholder="Count" type="number">
<input name="price[]" id="price_1" tabindex="1" value="" readonly="" placeholder="Full Price" type="currency">
And whenever adding new rows, just increment the id, but do not change names.
In PHP, you will be able to loop through posted array and insert each row into you database. Here is an example
for($i=0; $i < count($_POST['product_id']); $i++) {
$productid = $_POST['product_id'][i];
$lprice = $_POST['lprice'][i];
$count = $_POST['count'][i];
$lprice = $_POST['price'][i];
//Insert a row with $productid, $lprice, $count, $lprice
}
Related
I have a web app downloads the user input in form of a text file. How can I modify the template of the text file which is getting downloaded. Is there any way.
The current format in which it is getting downloaded is:-
Name: Mike
Email: xyz#gmail.com
Test type: BFT
Product Type: RAID
Protocol Type: iSCSI
IP Address: 255.255.255.0
Chasis Inputs: 21
HBA_Ports:
MC_IP:
MC_Netmask:
MC_Gateway:
MC:
SC:
FU:
EC:
Controller_ID:
The expected way I am looking for it to download is
Name: Mike
Email: xyz#gmail.com
Test type: BFT
IP Address: 255.255.255.0
product Type: RAID
Protocol Type: iSCSI
-Controller_ID:
-Chasis Inputs: 21
-HBA_Ports:
-MC_IP:
-MC_Netmask:
-MC_Gateway:
-MC:
-SC:
-FU:
-EC:
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information</h1>
<style>
html,
html * {
box-sizing: border-box;
border-color: teal;
font-family: calibri;
}
html {
background: radial-gradient(
rgba(48, 97, 97, 0.5),
rgba(255, 255, 255, 0.5)
);
}
input[type="button"],
input[type="submit"] {
padding: 1rem;
}
input[type="text"],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color: teal;
}
fieldset {
border: none;
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: "Times New Roman", Times, serif;
}
#extra {
border: 2px solid black;
background: whitesmoke;
border-radius: 1rem;
box-shadow: 0 0 5px black;
width: calc(100% - 24px);
margin: auto;
float: none;
clear: both;
}
#extra h6 {
margin: 0;
}
.invalid {
border: 2px solid red !important;
background: rgba(255, 0, 0, 0.1);
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
const extra = {};
const oForm = document.forms.myForm;
const oSave = document.querySelector('input[name="save"]');
const oSub = document.querySelector('input[name="submit"]');
const oCtrl = document.querySelector('select[name="controller"]');
const oTest = document.querySelector('select[name="test"]');
const oProto = document.querySelector('select[name="protocol"]');
const oTmp = document.querySelector("template");
const changehandler = function(e) {
let option = this.options[this.options.selectedIndex];
if (option.hasAttribute("data-extra")) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (Object.keys(extra).length == 2) {
let fieldset = oTmp.content.cloneNode(true);
oForm.insertBefore(fieldset, oProto.parentNode.nextSibling);
} else {
if (document.getElementById("extra")) {
fieldset = document.getElementById("extra");
fieldset.parentNode.removeChild(fieldset);
}
}
if (option.hasAttribute("data-extra")) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
/*
if( option.hasAttribute( 'data-RBOD' ) ) extra[ this.name ]=this.value;
else{
if( extra.hasOwnProperty( this.name ) )delete extra[ this.name ];
}
*/
if (this.name == "controller") {
if (this.value == "RAID") oProto.disabled = false;
else oProto.disabled = true;
}
};
const dialog = function(msg) {
alert(msg);
return false;
};
const savehandler = function(e) {
e.preventDefault();
let valid = true;
/*[ 'name','email','test','controller','ip','chassis' ].forEach( n => {
oForm[ n ].classList.remove('invalid');
if( oForm[ n ].value=='' ){
oForm[ n ].classList.add('invalid');
valid=false;
}
});*/
if (!valid) return dialog("Please fill all the fields!");
const reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(oForm.email.value) == false) {
return dialog("Invalid Email Address");
}
const ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(oForm.ip.value) == false) {
return dialog("Invalid IP Address");
}
if (oForm.name.value.length < 3)
return dialog("Name must be having atleast 3 Characters");
let data = {
Name: oForm.name.value,
Email: oForm.email.value,
"Test type": oForm.test.value,
"Product Type": oForm.controller.value,
"Protocol Type": oForm.protocol.value,
"IP Address": oForm.ip.value,
"Chasis Inputs": oForm.chassis.value
};
if (Object.keys(extra).length == 2) {
data["HBA_Ports"] = oForm["hba-ports"].value;
data["MC_IP"] = oForm["extra-ip"].value;
data["MC_Netmask"] = oForm["netmask-ip"].value;
data["MC_Gateway"] = oForm["gateway-ip"].value;
data["MC"] = oForm["rbod-mc"].value;
data["SC"] = oForm["rbod-sc"].value;
data["FU"] = oForm["rbod-fu"].value;
data["EC"] = oForm["rbod-ec"].value;
data["Controller_ID"] = oForm["Controller-ID"].value;
}
let payload = Object.keys(data)
.map(key => {
return [key, data[key]].join(": ");
})
.join(String.fromCharCode(10));
const blob = new Blob([payload], { type: "text/plain" });
const file = "formData.yaml";
let link = document.createElement("a");
link.download = file;
if (window.webkitURL != null) {
link.href = window.webkitURL.createObjectURL(blob);
} else {
link.href = window.URL.createObjectURL(blob);
link.style.display = "none";
document.body.appendChild(link);
}
link.click();
};
oCtrl.addEventListener("change", changehandler);
oTest.addEventListener("change", changehandler);
oSave.addEventListener("click", savehandler);
});
</script>
</head>
<body>
<template>
<fieldset id="extra">
<h6>Additional Details Required</h6>
<label for="Controller_ID">Controller_ID:</label>
<select name="Controller-ID" required>
<option value=""> - Select the Controller ID - </option>
<option value="A">A </option
><option value="B">B </option></select
>
<label for="HBA_Ports">HBA_Ports:</label
><input
type="text"
name="hba-ports"
placeholder="Enter the HBA Ports"
/>
<label for="MC_IP">MC_IP:</label
><input type="text" name="extra-ip" placeholder="Enter the MC_IP" />
<label for="MC_Netmask">MC_Netmask:</label
><input
type="text"
name="netmask-ip"
placeholder="Enter the MC_Netmask"
/>
<label for="MC_Gateway">MC_Gateway:</label
><input
type="text"
name="gateway-ip"
placeholder="Enter the MC_Gateway"
/>
<label for="MC">MC:</label
><input type="text" name="rbod-mc" placeholder="Enter the MC Port" />
<label for="SC">SC:</label
><input type="text" name="rbod-sc" placeholder="Enter the SC Port" />
<label for="FU">FU:</label
><input type="text" name="rbod-fu" placeholder="Enter the FU Port" />
<label for="EC">EC:</label
><input type="text" name="rbod-ec" placeholder="Enter the EC Port" />
</fieldset>
</template>
<form name="myForm" method="POST">
<fieldset>
<label for="Name">Name</label>
<input type="text" name="name" placeholder="Enter your name" required />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input
type="text"
name="email"
placeholder="Enter your Email Id"
required
/>
</fieldset>
<fieldset>
<label for="Controller Type">Controller Type</label>
<select name="controller" required>
<option value=""> - Select the Controller - </option>
<option data-extra="true" value="RAID">RAID </option
><option value="JBOD">JBOD </option
><option value="AP">AP </option></select
>
</fieldset>
<fieldset>
<label for="Test Type">Test Type</label>
<select name="test" required>
<option value=""> - Select The Test - </option>
<option data-extra="true" value="BFT">BFT </option
><option data-extra="true" value="CTO">CTO </option
><option data-extra="true" value="RAID Generic">RAID Generic </option
><option data-extra="true" value="Port Check">Port Check </option
><option data-extra="true" value="FW Generic">FW Generic </option
><option data-extra="true" value="JBOD Generic"
>JBOD Generic
</option></select
>
</fieldset>
<!-- insert templated additional details here -->
<fieldset>
<label for="Protocol Type">Protocol Type</label>
<select name="protocol" disabled>
<option selected hidden disabled> - Select The Protocol - </option
><option data-extra="true" value="SAS">SAS </option
><option data-extra="true" value="iSCSI">iSCSI </option
><option data-extra="true" value="FC">FC </option></select
>
</fieldset>
<fieldset>
<label for="IP Address">IP Address:</label>
<input
type="text"
name="ip"
placeholder="Enter your IP address"
required
/>
</fieldset>
<fieldset>
<label for="Chasis Input">Number of Chasis Input:</label>
<input
type="number"
name="chassis"
placeholder="Enter Number of Chasis"
required
/>
</fieldset>
<fieldset>
<input type="button" name="save" value="Save data to file" />
</fieldset>
</form>
</body>
</html>
I have built an app using html,js and css. The output of the web app is a text or yaml file. I am inputing the data and trying to gather in a yaml file. The code is given below:-
For instance, I want the 'PDU' data in the downloaded file to be like this
PDU:
PDU_IP: 10.235.250.49 (this is just a sample IP)
While I am trying to do this, its showing [object Object]. I tried to use stringify to convert object to string but failed in realizing the following funcionality. can anyone please help me in formatting the downloaded data. Basically i want the data to be in the format as it is there in a YAML file.
document.addEventListener('DOMContentLoaded', function() {
const extra = {};
const oForm = document.forms.myForm;
const oSave = document.querySelector('input[name="save"]');
const oSub = document.querySelector('input[name="submit"]');
const oCtrl = document.querySelector('select[name="controller"]');
const oTest = document.querySelector('select[name="test"]');
const oProto = document.querySelector('select[name="protocol"]');
const oTmp = document.querySelector('template');
const changehandler = function(e) {
let option = this.options[this.options.selectedIndex];
if (option.hasAttribute('data-extra')) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (Object.keys(extra).length == 2) {
let fieldset = oTmp.content.cloneNode(true);
oForm.insertBefore(fieldset, oProto.parentNode.nextSibling)
} else {
if (document.getElementById('extra')) {
fieldset = document.getElementById('extra')
fieldset.parentNode.removeChild(fieldset);
}
}
if (option.hasAttribute('data-extra')) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (this.name == 'controller') {
if (this.value == 'RAID') oProto.disabled = false
else oProto.disabled = true
}
}
const dialog = function(msg) {
alert(msg);
return false;
}
const savehandler = function(e) {
e.preventDefault();
let valid = true;
/*[ 'name','email','test','controller','ip','chassis' ].forEach( n => {
oForm[ n ].classList.remove('invalid');
if( oForm[ n ].value=='' ){
oForm[ n ].classList.add('invalid');
valid=false;
}
});*/
if (!valid) return dialog('Please fill all the fields!');
const ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(oForm.ip.value) == false) {
return dialog('Invalid IP Address');
}
let data = {
"PDU": {
"PDU TEST": oForm.test.value,
"PDU_IP": oForm.ip.value
},
'Product Type': oForm.controller.value,
'Protocol Type': oForm.protocol.value,
'Chasis Inputs': oForm.chassis.value
};
var datastr = JSON.stringify(data);
if (Object.keys(extra).length == 2) {
data[' - #Controller_ID_A'] = oForm['Controller-ID1'].value;
data[' HBA_Ports_A'] = [oForm['hba-ports1'].value];
data[' MC_IP_A'] = oForm['extra-ip1'].value;
data[' MC_Netmask_A'] = oForm['netmask-ip1'].value;
data[' MC_Gateway_A'] = oForm['gateway-ip1'].value;
data[' MC_A'] = oForm['rbod-mc1'].value;
data[' SC_A'] = oForm['rbod-sc1'].value;
data[' FU_A'] = oForm['rbod-fu1'].value;
data[' EC_A'] = oForm['rbod-ec1'].value;
}
if (Object.keys(extra).length == 2) {
data[' - #Controller_ID'] = oForm['Controller-ID'].value;
data[' HBA_Ports'] = [oForm['hba-ports'].value];
data[' MC_IP'] = oForm['extra-ip'].value;
data[' MC_Netmask'] = oForm['netmask-ip'].value;
data[' MC_Gateway'] = oForm['gateway-ip'].value;
data[' MC'] = oForm['rbod-mc'].value;
data[' SC'] = oForm['rbod-sc'].value;
data[' FU'] = oForm['rbod-fu'].value;
data[' EC'] = oForm['rbod-ec'].value;
}
let payload = Object.keys(data).map(key => {
return [key, data[key]].join(': ')
}).join(String.fromCharCode(10));
const blob = new Blob([payload], {
type: 'text/plain'
});
const file = 'formData.yaml';
let link = document.createElement('a');
link.download = file;
if (window.webkitURL != null) {
link.href = window.webkitURL.createObjectURL(blob);
} else {
link.href = window.URL.createObjectURL(blob);
link.style.display = "none";
document.body.appendChild(link);
}
link.click();
}
oCtrl.addEventListener('change', changehandler);
oTest.addEventListener('change', changehandler);
oSave.addEventListener('click', savehandler);
})
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information </h1>
<style>
html,
html * {
box-sizing: border-box;
border-color: teal;
font-family: calibri;
}
html {
background: radial-gradient(rgba(48, 97, 97, 0.5), rgba(255, 255, 255, 0.5))
}
input[type=button],
input[type=submit] {
padding: 1rem;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color: teal
}
fieldset {
border: none;
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
#extra {
border: 2px solid black;
background: whitesmoke;
border-radius: 1rem;
box-shadow: 0 0 5px black;
width: calc(100% - 24px);
margin: auto;
float: none;
clear: both;
text-indent: 50px;
}
#extra h6 {
margin: 0
}
#extra style .invalid {
border: 2px solid red!important;
background: rgba(255, 0, 0, 0.1)
}
</style>
<script src="script.js"></script>
</head>
<body>
<template>
<fieldset id='extra'>
<h6>Additional Details Required</h6>
<label for='Controller_ID_A'>Controller_ID:</label>
<select name='Controller-ID1' required>
<option value=""> - Select the Controller ID - </option>
<option value='A'>A </select>
<label for='HBA_Ports_A'>HBA_Ports:</label><input type='text' name='hba-ports1' placeholder='Enter the HBA Ports' />
<label for='MC_IP_A'>MC_IP:</label><input type='text' name='extra-ip1' placeholder='Enter the MC_IP' />
<label for='MC_Netmask_A'>MC_Netmask:</label><input type='text' name='netmask-ip1' placeholder='Enter the MC_Netmask' />
<label for='MC_Gateway_A'>MC_Gateway:</label><input type='text' name='gateway-ip1' placeholder='Enter the MC_Gateway' />
<label for='MC_A'>MC:</label><input type='text' name='rbod-mc1' placeholder='Enter the MC Port' />
<label for='SC_A'>SC:</label><input type='text' name='rbod-sc1' placeholder='Enter the SC Port' />
<label for='FU_A'>FU:</label><input type='text' name='rbod-fu1' placeholder='Enter the FU Port' />
<label for='EC_A'>EC:</label><input type='text' name='rbod-ec1' placeholder='Enter the EC Port' />
<label for='Controller_ID'>Controller_ID:</label>
<select name='Controller-ID' required>
<option value=""> - Select the Controller ID - </option>
<option value='B'>B </select>
<label for='HBA_Ports'>HBA_Ports:</label><input type='text' name='hba-ports' placeholder='Enter the HBA Ports' />
<label for='MC_IP'>MC_IP:</label><input type='text' name='extra-ip' placeholder='Enter the MC_IP' />
<label for='MC_Netmask'>MC_Netmask:</label><input type='text' name='netmask-ip' placeholder='Enter the MC_Netmask' />
<label for='MC_Gateway'>MC_Gateway:</label><input type='text' name='gateway-ip' placeholder='Enter the MC_Gateway' />
<label for='MC'>MC:</label><input type='text' name='rbod-mc' placeholder='Enter the MC Port' />
<label for='SC'>SC:</label><input type='text' name='rbod-sc' placeholder='Enter the SC Port' />
<label for='FU'>FU:</label><input type='text' name='rbod-fu' placeholder='Enter the FU Port' />
<label for='EC'>EC:</label><input type='text' name='rbod-ec' placeholder='Enter the EC Port' />
</fieldset>
</template>
<form name='myForm' method='POST'>
<fieldset>
<label for='Controller Type'>Controller Type</label>
<select name='controller' required>
<option value=""> - Select the Controller - </option>
<option data-extra=true value='RAID'>RAID
<option data-extra=true value='JBOD'>JBOD
<option data-extra=true value='AP'>AP
</select>
</fieldset>
<fieldset>
<label for='Test Type'>Test Type</label>
<select name='test' required>
<option value=""> - Select The Test - </option>
<option data-extra=true value='BFT'>BFT
<option data-extra=true value='CTO'>CTO
<option data-extra=true value='RAID Generic'>RAID Generic
<option data-extra=true value='Port Check'>Port Check
<option data-extra=true value='FW Generic'>FW Generic
<option data-extra=true value='JBOD Generic'>JBOD Generic
</select>
</fieldset>
<!-- insert templated additional details here -->
<fieldset>
<label for='Protocol Type'>Protocol Type</label>
<select name='protocol' required>
<option value=""> - Select The Protocol -
<option data-extra=true value='SAS'>SAS
<option data-extra=true value='iSCSI'>iSCSI
<option data-extra=true value='FC'>FC
</select>
</fieldset>
<fieldset>
<label for='IP Address'>IP Address:</label>
<input type='text' name='ip' placeholder='Enter your IP address' required />
</fieldset>
<fieldset>
<label for='Chasis Input'>Number of Chasis Input:</label>
<input type='number' name='chassis' placeholder='Enter Number of Chasis' required />
</fieldset>
<fieldset>
<input type='button' name='save' value='Save data to file' />
</fieldset>
</form>
</body>
</html>
Take a look at this snippet. It's mostly your code, but I changed the part where you create the payload.
I marked my changes with MY CHANGE BEGINS HERE and MY CHANGE ENDS HERE comments.
It adds spaces dynamically, so the format looks like this:
PDU:
PDU TEST: BFT
PDU_IP: 185.237.96.51
Product Type:
Protocol Type: iSCSI
Chasis Inputs:
However, it does not work with the rest of your fields, but maybe you can use it to replace your hacky whitespacing by creating plain objects and adding them to your data.
document.addEventListener('DOMContentLoaded', function() {
const extra = {};
const oForm = document.forms.myForm;
const oSave = document.querySelector('input[name="save"]');
const oSub = document.querySelector('input[name="submit"]');
const oCtrl = document.querySelector('select[name="controller"]');
const oTest = document.querySelector('select[name="test"]');
const oProto = document.querySelector('select[name="protocol"]');
const oTmp = document.querySelector('template');
const changehandler = function(e) {
let option = this.options[this.options.selectedIndex];
if (option.hasAttribute('data-extra')) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (Object.keys(extra).length == 2) {
let fieldset = oTmp.content.cloneNode(true);
oForm.insertBefore(fieldset, oProto.parentNode.nextSibling)
} else {
if (document.getElementById('extra')) {
fieldset = document.getElementById('extra')
fieldset.parentNode.removeChild(fieldset);
}
}
if (option.hasAttribute('data-extra')) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (this.name == 'controller') {
if (this.value == 'RAID') oProto.disabled = false
else oProto.disabled = true
}
}
const dialog = function(msg) {
alert(msg);
return false;
}
const savehandler = function(e) {
e.preventDefault();
let valid = true;
/*[ 'name','email','test','controller','ip','chassis' ].forEach( n => {
oForm[ n ].classList.remove('invalid');
if( oForm[ n ].value=='' ){
oForm[ n ].classList.add('invalid');
valid=false;
}
});*/
if (!valid) return dialog('Please fill all the fields!');
const ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(oForm.ip.value) == false) {
return dialog('Invalid IP Address');
}
let data = {
"PDU": {
"PDU TEST": oForm.test.value,
"PDU_IP": oForm.ip.value
},
'Product Type': oForm.controller.value,
'Protocol Type': oForm.protocol.value,
'Chasis Inputs': oForm.chassis.value
};
var datastr = JSON.stringify(data);
if (Object.keys(extra).length == 2) {
data[' - #Controller_ID_A'] = oForm['Controller-ID1'].value;
data[' HBA_Ports_A'] = [oForm['hba-ports1'].value];
data[' MC_IP_A'] = oForm['extra-ip1'].value;
data[' MC_Netmask_A'] = oForm['netmask-ip1'].value;
data[' MC_Gateway_A'] = oForm['gateway-ip1'].value;
data[' MC_A'] = oForm['rbod-mc1'].value;
data[' SC_A'] = oForm['rbod-sc1'].value;
data[' FU_A'] = oForm['rbod-fu1'].value;
data[' EC_A'] = oForm['rbod-ec1'].value;
}
if (Object.keys(extra).length == 2) {
data[' - #Controller_ID'] = oForm['Controller-ID'].value;
data[' HBA_Ports'] = [oForm['hba-ports'].value];
data[' MC_IP'] = oForm['extra-ip'].value;
data[' MC_Netmask'] = oForm['netmask-ip'].value;
data[' MC_Gateway'] = oForm['gateway-ip'].value;
data[' MC'] = oForm['rbod-mc'].value;
data[' SC'] = oForm['rbod-sc'].value;
data[' FU'] = oForm['rbod-fu'].value;
data[' EC'] = oForm['rbod-ec'].value;
}
// MY CHANGE BEGINS HERE <-------
let payload = '';
const addToPayload = (object, whitespace) => {
for (const key of Object.keys(object)) {
payload += whitespace + key + ':';
const value = object[key];
if (typeof value === 'object') {
payload += String.fromCharCode(10);
addToPayload(value, whitespace + ' ');
} else {
payload += ' ' + value + String.fromCharCode(10);
}
}
}
addToPayload(data, '');
// MY CHANGE ENDS HERE <------------
const blob = new Blob([payload], {
type: 'text/plain'
});
const file = 'formData.yaml';
let link = document.createElement('a');
link.download = file;
if (window.webkitURL != null) {
link.href = window.webkitURL.createObjectURL(blob);
} else {
link.href = window.URL.createObjectURL(blob);
link.style.display = "none";
document.body.appendChild(link);
}
link.click();
}
oCtrl.addEventListener('change', changehandler);
oTest.addEventListener('change', changehandler);
oSave.addEventListener('click', savehandler);
})
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information </h1>
<style>
html,
html * {
box-sizing: border-box;
border-color: teal;
font-family: calibri;
}
html {
background: radial-gradient(rgba(48, 97, 97, 0.5), rgba(255, 255, 255, 0.5))
}
input[type=button],
input[type=submit] {
padding: 1rem;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color: teal
}
fieldset {
border: none;
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
#extra {
border: 2px solid black;
background: whitesmoke;
border-radius: 1rem;
box-shadow: 0 0 5px black;
width: calc(100% - 24px);
margin: auto;
float: none;
clear: both;
text-indent: 50px;
}
#extra h6 {
margin: 0
}
#extra style .invalid {
border: 2px solid red!important;
background: rgba(255, 0, 0, 0.1)
}
</style>
<script src="script.js"></script>
</head>
<body>
<template>
<fieldset id='extra'>
<h6>Additional Details Required</h6>
<label for='Controller_ID_A'>Controller_ID:</label>
<select name='Controller-ID1' required>
<option value=""> - Select the Controller ID - </option>
<option value='A'>A </select>
<label for='HBA_Ports_A'>HBA_Ports:</label><input type='text' name='hba-ports1' placeholder='Enter the HBA Ports' />
<label for='MC_IP_A'>MC_IP:</label><input type='text' name='extra-ip1' placeholder='Enter the MC_IP' />
<label for='MC_Netmask_A'>MC_Netmask:</label><input type='text' name='netmask-ip1' placeholder='Enter the MC_Netmask' />
<label for='MC_Gateway_A'>MC_Gateway:</label><input type='text' name='gateway-ip1' placeholder='Enter the MC_Gateway' />
<label for='MC_A'>MC:</label><input type='text' name='rbod-mc1' placeholder='Enter the MC Port' />
<label for='SC_A'>SC:</label><input type='text' name='rbod-sc1' placeholder='Enter the SC Port' />
<label for='FU_A'>FU:</label><input type='text' name='rbod-fu1' placeholder='Enter the FU Port' />
<label for='EC_A'>EC:</label><input type='text' name='rbod-ec1' placeholder='Enter the EC Port' />
<label for='Controller_ID'>Controller_ID:</label>
<select name='Controller-ID' required>
<option value=""> - Select the Controller ID - </option>
<option value='B'>B </select>
<label for='HBA_Ports'>HBA_Ports:</label><input type='text' name='hba-ports' placeholder='Enter the HBA Ports' />
<label for='MC_IP'>MC_IP:</label><input type='text' name='extra-ip' placeholder='Enter the MC_IP' />
<label for='MC_Netmask'>MC_Netmask:</label><input type='text' name='netmask-ip' placeholder='Enter the MC_Netmask' />
<label for='MC_Gateway'>MC_Gateway:</label><input type='text' name='gateway-ip' placeholder='Enter the MC_Gateway' />
<label for='MC'>MC:</label><input type='text' name='rbod-mc' placeholder='Enter the MC Port' />
<label for='SC'>SC:</label><input type='text' name='rbod-sc' placeholder='Enter the SC Port' />
<label for='FU'>FU:</label><input type='text' name='rbod-fu' placeholder='Enter the FU Port' />
<label for='EC'>EC:</label><input type='text' name='rbod-ec' placeholder='Enter the EC Port' />
</fieldset>
</template>
<form name='myForm' method='POST'>
<fieldset>
<label for='Controller Type'>Controller Type</label>
<select name='controller' required>
<option value=""> - Select the Controller - </option>
<option data-extra=true value='RAID'>RAID
<option data-extra=true value='JBOD'>JBOD
<option data-extra=true value='AP'>AP
</select>
</fieldset>
<fieldset>
<label for='Test Type'>Test Type</label>
<select name='test' required>
<option value=""> - Select The Test - </option>
<option data-extra=true value='BFT'>BFT
<option data-extra=true value='CTO'>CTO
<option data-extra=true value='RAID Generic'>RAID Generic
<option data-extra=true value='Port Check'>Port Check
<option data-extra=true value='FW Generic'>FW Generic
<option data-extra=true value='JBOD Generic'>JBOD Generic
</select>
</fieldset>
<!-- insert templated additional details here -->
<fieldset>
<label for='Protocol Type'>Protocol Type</label>
<select name='protocol' required>
<option value=""> - Select The Protocol -
<option data-extra=true value='SAS'>SAS
<option data-extra=true value='iSCSI'>iSCSI
<option data-extra=true value='FC'>FC
</select>
</fieldset>
<fieldset>
<label for='IP Address'>IP Address:</label>
<input type='text' name='ip' placeholder='Enter your IP address' required />
</fieldset>
<fieldset>
<label for='Chasis Input'>Number of Chasis Input:</label>
<input type='number' name='chassis' placeholder='Enter Number of Chasis' required />
</fieldset>
<fieldset>
<input type='button' name='save' value='Save data to file' />
</fieldset>
</form>
</body>
</html>
You commented that you would prefer dynamic filenames. You can replace
const file = 'formData.yaml';
with something like this:
let file = 'test_' + data.PDU['PDU TEST'];
file += '_controller_' + data['Product Type'];
file += '_' + new Date().toISOString().substr(0, 10); // '2020-05-02'
file += '.yaml';
file = prompt('Filename:', file); // to edit manually
if (!file) { return; } // canceled by user
I'm trying to create a BMR calculation embedded in my site. I have it working except for the gender portion (if male vs female, different calculations)
I understand that I need an adlistener but doesn't seem to be working. I think I am not referencing it properly.
Here's my code:
var theForm = document.forms["RMRform"];
var bmr;
function RMRcalc() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var gender = document.getElementById("gender").value;
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
var activitylevel = new Array();
activitylevel["sedentary"] = 1.2;
activitylevel["low"] = 1.3;
activitylevel["moderate"] = 1.5;
activitylevel["high"] = 1.7;
function getActivityLevel() {
var activityLevelamount = 0;
var theForm = document.forms["RMRform"];
var selectedActivity = theForm.elements["activity"];
activityLevelamount = activitylevel[selectedActivity.value];
return activityLevelamount;
}
if (i = this) {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) - 161) * getActivityLevel();
} else {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) + 5) * getActivityLevel();
}
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
RMRcalc();
document.getElementById('results').innerHTML = bmr;
})
body {
font: 15px gothic, sans-serif;
letter-spacing: 1px;
}
input {
width: 100%;
}
input[type=number] {
border: none;
border-bottom: 1px solid grey;
}
button[type=button] {
background-color: #ddcecb;
border: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
color: #95483e;
padding: 16px 32px;
text-decoration: none;
letter-spacing: 1px;
margin: 4px 2px;
}
input[type=text]:focus {
border: 1px solid #555;
}
.form-inline label {
margin: 5px 10px 5px 0;
}
#media (max-width: 800px) {
.form-inline input {
margin: 10px 0;
}
.form-inline {
flex-direction: column;
align-items: stretch;
}
<form action="" id="RMRform">
<label for='gender' class="inlinelabel">
Female </label>
<input type="radio" id="gender" name="gender" value="fem" checked onclick="RMRcalc()" /><br>
<label for='gender' class="inlinelabel">
Male </label>
<input type="radio" id="gender" name='gender' value="masc" onclick="RMRcalc()" /> <br> Weight (kg):<br>
<input type="number" id="weight"><br><br> Height (cm):<br>
<input type="number" id="height"><br><br> Age (years):<br>
<input type="number" id="age"><br><br> Activity Level:
<select id="activity" name="activity">
<option value="sedentary">sedentary (1-2x/week)</option>
<option value="low">low (2-3x/week)</option>
<option value="moderate">moderate (3-4x/week)</option>
<option value="high">high (5x/week)</option>
</select>
</form> <br>
<button type="button" onclick="">
calculate</button>
<p>Your Daily Estimated Requirements</p>
<div id="results"></div>
With this, there's just no calculation showing.
Thanks in advance!
A closing } is missing for the #media query.
There shouldn't be a variable declaration in your if condition: if (var i=this). Remove the var.
Both of your radio input have the same id="gender". Id's should be unique. Consider using a class instead. This will cause problems when you later use the gender variable for your if male vs female calculations because of this selector:
var gender = document.getElementById("gender").value;
For rad to be defined in your loop...
var rad = document.myForm.myRadios;
...you'll need to change myRadios to gender, because that's the name of your radio inputs. You'll also need to give your form the name myForm.
<form action="" id="RMRform" name="myForm">
Perhaps you're looking for something in this region...
function calc () {
const gender = document.querySelector('input[name="gender"]:checked').value,
weight = document.getElementById('weight').value,
height = document.getElementById('height').value,
age = document.getElementById('age').value,
activity = document.getElementById('activity').value;
// calculate base metric value
let metricBase = ((10 * weight) + (6.25 * height) - (5 * age));
// calculate per gender
metricBase = (gender === 'fem') ? metricBase - 161 : metricBase + 5;
// calculate with inline activity values
const bmr = Math.round( metricBase * parseFloat(activity) );
// format caloric intake output
document.getElementById('results').innerHTML = `${bmr.toLocaleString()} calories/day`;
}
// prevents form change listener until after first calculation
let firstCalc = true;
document.getElementById('calc').addEventListener('click', () => {
if (firstCalc) document.querySelector('form').onchange = calc;
firstCalc = false;
calc();
}, false);
body {
}
body, input {
font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
font-size: 14px;
letter-spacing: 1px;
}
input[type="radio"] {
display: inline-block;
width: 1rem;
}
input[type="number"] {
border: none;
border-bottom: 1px solid #ccc;
}
.group {
padding: .5rem 0;
}
<form>
<div class="group">
<label class="radio">
<input type="radio" name="gender" value="fem" checked />
Female
</label>
<label class="radio">
<input type="radio" name='gender' value="masc" />
Male
</label>
</div>
<div class="group">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" value="79" />
</div>
<div class="group">
<label for="weight">Height (cm):</label>
<input type="number" id="height" value="172" />
</div>
<div class="group">
<label for="weight">Age (years):</label>
<input type="number" id="age" value="22" />
</div>
<div class="group">
<label for="activity">Activity Level:</label>
<select id="activity">
<option value="1.2" selected>Sedentary (1-2x/week)</option>
<option value="1.3">Low (2-3x/week)</option>
<option value="1.5">Moderate (3-4x/week)</option>
<option value="1.7">High (5x/week)</option>
</select>
</div>
<button type="button" id="calc">Calculate</button>
</form>
<p id="results"></p>
Here is what i see (i am quite new to JS so i may not see everything) :
There is no opening head tag (not sure if that's a problem).
The gender radio buttons both have the same id. IDs should be unique. And because of this my guess is that this code should only give you the value for fem no ?:
html:
<input type="radio" id="gender" name="gender" value="fem" checked
onclick="RMRcalc()" />
<input type="radio" id="gender" name='gender' value="masc"
onclick="RMRcalc()" />
js:
var gender = document.getElementById("gender").value;
In your for-loops i would use let instead of var, otherwise you might get in trouble someday. Checkout this post.
for (let i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
I didn't understand this in your function RMRcalc : if (var i = this)
I have two forms. I want one of them to be enabled by the user choose through one of the radio buttons above.
What I want to do is to get the value of radio button and through this value make one of the forms enable.
So I try with JavaScript and input radio ID but I had no success:
<script>
window.addEventListener('load', init);
function init(){
var radio = document.getElementsByName ("questions");
for (var i=0; i<radios.length; i++) {
if(radio[i].getElementById.checked == "questions_1") {
radio[i].addEventListener(seleccionar);
}
}
function trigger() {
elementsForm = document.forms['question'].elements;
for (var y=0; y<elementsForm.length; y++) {
elementsForm[y].disabled=false;
}
}
</script>
Here's my code (HTML and CSS):
.category_1 {
height: 50px;
padding-top: 2%;
}
.question {
display: inline-flex;
margin-left: 5%;
}
.q-text {
font-weight: 600;
}
.q1 {
width: 44%;
}
.q2 {
width: 44%;
}
.form {
display: inline-flex;
margin-left: 5%;
}
.form.q1 {
width: 44%;
}
.form.q2 {
width: 44%;
}
.data {
margin-top: 5%;
}
.data label {
opacity: 0.5;
}
input[type=text] {
width: 100%;
}
select {
width: 100%;
}
textarea {
width: 98%;
}
input[type=submit] {
display: block;
margin: auto;
}
<body>
<div class="category_1">
<div class="question q1"><input type="radio" name="question" value="question_1" id="question_1">
<div class="q-text">QUESTION 1</div></div>
<div class="question q2"><input type="radio" name="question" value="question_2" id="question_2">
<div class="q-text">QUESTION 2</div></div>
</div>
<div class="form q1">
<form name="q1" method="post" action="">
<div class ="data">
<label for="others">Name:</label>
<input type="text" name="name" disabled>
</div>
<div class="data">
<label for="others">Select an item:</label>
<select name="items-q1" disabled>
<option value="it1">item 1</option>
<option value="it2">item 2</option>
<option value="it3">item 3</option>
<option value="it4">item 4</option>
</select>
</div>
<div class="data">
<label for="others">Anything else?</label>
<textarea name="more" disabled></textarea>
</div>
<div class="data">
<input type="submit" value="submit" disabled>
</div>
</form>
</div>
<div class="form q2">
<form name="q2" method="post" action="">
<div class ="data">
<label for="others">Name:</label>
<input type="text" name="name" disabled>
</div>
<div class ="data">
<label for="others">Choose an option:</label><br>
<input type="radio" name="option" value="o1" disabled><label for="others">1</label>
<input type="radio" name="option" value="o2" disabled><label for="others">2</label>
</div>
<div class="data">
<label for="others">Anything else?</label>
<textarea name="more" disabled></textarea>
</div>
<div class="data">
<input type="submit" value="submit" disabled>
</div>
</form>
</div>
</body>
I'd really appreciate any suggestions.
First of all i noticed your are getting the radios by the wrong name
its "question" not "questions"
<script>
var rad = document.getElementsByName('question');
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
if(this.value == "questions_1") {
//input logic to display form
//This is where you run isTrue() Function
isTrue(data);
}
else{
//This is where you run isFalse() function
isFalse(data);
}
};
}
//Function to run if its true
function isTrue(data){
//something equals something
}
//Function to run if its false
function isFalse(data){
//something equals something
}
</script>
Reference Link
<script>
var rad = document.getElementsByName('question');
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function () {
if(this.value == "question_1") {
e1();
}else {
e2();
}
};
}
function e1() {
var eform1 = document.querySelectorAll('.q1 input[type=text], .q1 select, .q1 textarea, .q1 input[type=submit]');
for(var i = 0; i < eform1.length; i++) {
eform1[i].disabled = false;
}
}
function e2() {
var eform2 = document.querySelectorAll('.q2 input[type=text], .q2 input[type=radio], .q2 textarea, .q2 input[type=submit]');
for(var i = 0; i < eform2.length; i++) {
eform2[i].disabled = false;
}
}
</script>
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help?
Here is my jsfiddle http://jsfiddle.net/clbacon70/x6kjqbop/1/
var gc_fSandwichPrice = 5.99; // Price for each sandwich
var gc_fExtrasPrice = 1.50; // Price for each extra item
// GLOBAL VARS
// Global object vars
var divErrors;
var radSandwich;
var radSize;
var chkExtras;
// Other global vars
var g_fTotal;
var g_sSandwich;
var g_sSize;
var g_sExtras;
window.addEventListener('load', Init);
function Init() {
document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0";
var spanExtrasPrice = document.getElementById("spanExtrasPrice");
var btnCalculateTotal = document.getElementById("btnCalculateTotal");
divErrors = document.getElementById("divErrors");
radSandwich = document.getElementsByName('radSandwich');
radSize = document.getElementsByName('radSize');
chkExtras = document.getElementsByName('chkExtras');
spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2);
btnCalculateTotal.addEventListener('click', CalculateTotal);
} // function Init()
function CalculateTotal() {
divErrors.innerHTML = '';
if (radSandwich[0].checked) {
g_sSandwich = radSandwich[0].value;
} else if (radSandwich[1].checked) {
g_sSandwich = radSandwich[1].value;
} else if (radSandwich[2].checked) {
g_sSandwich = radSandwich[2].value;
} else if (radSandwich[3].checked) {
g_sSandwich = radSandwich[3].value;
} else {
divErrors.innerHTML = "Select a Sandwich";
return;
}
if (radSize[0].checked){
g_fTotal = radSize[0].title;
} else if (radSize[1].checked) {
g_fTotal = radSize[1].title;
} else if (radSize[2].checked) {
g_fTotal = radSize[2].title;
} else {
divErrors.innerHTML = "Please choose a size";
return;
}
if (chkExtras[0].checked) {
g_sExtras = chkExtras[0].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
if (chkExtras[1].checked) {
g_sExtras = g_sExtras + ',' + chkExtras[1].value;
g_fTotal = g_fTotal + gc_fExtrasPrice; }
if (chkExtras[2].checked) {
g_sExtras = g_sExtras +', ' + chkExtras[2].value;
g_fTotal = g_fTotal + gc_fExtrasPrice;
}
var textTotal = document.getElementById('textTotal');
textTotal.value = g_fTotal;
} // function CalculateTotal
function ProcessOrder() {
} // function ProcessOrder
* {
margin: 0;
padding: 0;
}
body {
background-color: #333;
}
#divWrapper {
background-color: #efe;
width: 40em;
border: solid black;
border-radius: 0 0 20px 20px;
border-width: 0 1px 1px 1px;
margin: 0 auto;
padding: 2em 1em;
}
h2 {
font-style: italic;
font-size: 1.3em;
color: #666;
margin-top: 0px;
}
input {
margin-right: 0.3em;
}
h3, p {
margin: 0.5em 0;
}
div#divErrors {
font-size: 110%;
color: white;
background: #f00;
margin-bottom: 0.5em;
}
#divPaymentInfo {
margin: 10px 0 20px 0;
padding-bottom: 10px;
border: solid black;
border-width: 1px 0;
}
#divCreditCardInfo {
font-size: .8em;
visibility: hidden;
margin-left: 1em;
display: inline;
}
#divOrder {
background: white;
min-height: 10em;
width: 25em;
border: 1px solid black;
margin: 0.5em 0;
padding: 10px;
}
<body>
<div id="divWrapper">
<form name="frmMain">
<h1 id="h1Title">Deli Form</h1>
<h2>Part 1</h2>
<h3>Sandwich</h3>
<label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br>
<label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br>
<label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br>
<label><input type="radio" name="radSandwich" value="ReelMeatĀ®">ReelMeatĀ®</label><br>
<br>
<h3>Size</h3>
<label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>
<label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>
<label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label>
<br><br>
<h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3>
<label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br>
<label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br>
<label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br>
<br><br>
Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total">
<br><br>
<div id="divErrors"></div>
<div id="divPaymentInfo">
<h2>Part 2</h2>
<strong>Customer's Name:</strong> <input type="text" id="txtName">
<br><br>
<strong>Payment:</strong>
<select id="selPayment">
<option value="Cash" selected="selected">Cash</option>
<option value="Check">Check</option>
<option value="Credit Card">Credit Card</option>
</select>
<div id="divCreditCardInfo">
Card Number: <input type="text" id="txtCreditCardNbr" size="20">
Month: <input type="text" id="txtMonth" size="2"> Year:
<select id="selYear">
<option value="" selected="selected"></option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2010">2017</option>
<option value="2011">2018</option>
</select>
</div><!-- divCreditCardInfo -->
</div><!-- divPaymentInfo -->
<input type="button" id="btnProcessOrder" value="Process Order">
<div id="divOrder"></div>
<input type="reset" value="Reset">
</form>
</div> <!-- divWrapper -->
</body>
You have a typo in your javascript. You are attempting to fetch an html element with id textTotal, when the field you're interesting in is actually given the id txtTotal.
Fix that typo and it will work.
var textTotal = document.getElementById('textTotal');
Your selector is wrong. The element id of your textbox is txtTotal
so the following should work:
var textTotal = document.getElementById('txtTotal');
Here's a fixed copy of your jsFiddle: http://jsfiddle.net/dcseekcw/
What I fixed:
You were passing in $ along with values you were trying to add as floats. Removed them from your title values and only put it back in after the total is calculated.
Put in parseFloat so values could be added together instead of being concatenated as strings.
Initialised your g_fTotal and chkExtras variables.
Put in some basic checking so that radSize doesn't cause problems when it's not selected.
You have to add brackets after 'Init'.
window.addEventListener('load', Init());
And also there was a typo in the end of CalculateTotal function.
Here is working example:
http://jsfiddle.net/x6kjqbop/3/