Adding the total for a form Javascript - javascript

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/

Related

Using eventlistener to disable and enable a button

I have a chess form with six fields. Two are drop down menus to select names (whiteplayername and blackplayername) and the other four can be used to add a custom name instead (firstnamewhite, lastnamewhite, firstnameblack, lastnameblack). Currently, I want my javascript to disable the custom fields if a name has been selected from the drop down menu (this is working). I also want the submit button to be disabled if neither the whiteplayername or firstnamewhite and blackplayername of firstnameblack is selected. Currently, the submit-button becomes enabled if a name is selected from both the blackplayername and whiteplayname menus but then does not become disabled again if an empty field is selected in either.
Edit
The full html is below, though I have taken out a section just made up of text and rows from the table in order to cut down on the space used.
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>chessopenings3</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
body {
style: "background-color: #FF0000;
}
.topnav {
position: relative;
overflow: hidden;
background-color: #333;
border: 2px;
width: max-content;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
border: 2px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
border: 2px;
}
.formformat {
color: white;
padding: 50px;
font-size: 24px;
font-family: Arial, Helvetica, sans-serif;
}
.instructions-text {
position: absolute;
color: white;
align: center;
left: 750px;
top: 150px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
.warning {
position: absolute;
color: white;
text-align: left;
left: 150px;
top: 50px;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
select {
width: 120px;
}
select:focus {
min-width: 120px;
width: auto;
}
#media screen and (max-width: 500px) {
.navbar a {
float: none;
display: block;
}
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
let isformvalid = false;
document.getElementById("submit-button").disabled = !isformvalid;
document.getElementById("whiteplayername").addEventListener("change", function () {
let blackplayername =
document.getElementById("blackplayername");
let firstnameblack =
document.getElementById("firstnameblack");
let firstnamewhite =
document.getElementById("firstnamewhite");
let lastnamewhite =
document.getElementById("lastnamewhite");
let lastnameblack =
document.getElementById("lastnameblack");
disablewhenmandatorynamemissingwhitename(this.value, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite);
isformvalid = checkeitherfirstorfullnamepopulated (this.value, firstnamewhite, blackplayername, firstnameblack, isformvalid);
document.getElementById("submit-button").disabled = !isformvalid;
});
});
function disablewhenmandatorynamemissingwhitename(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (whiteplayername !== "") {
firstnamewhite.disabled = true;
lastnamewhite.disabled = true;
} else {
firstnamewhite.disabled = false;
lastnamewhite.disabled = false;
}
}
function disablewhenmandatorynamemissingblackname(whiteplayername, blackplayername, firstnameblack, firstnamewhite, lastnameblack, lastnamewhite) {
if (blackplayername !== "") {
firstnameblack.disabled = true;
lastnameblack.disabled = true;
} else {
firstnameblack.disabled = false;
lastnameblack.disabled = false;
}
};
function checkeitherfirstorfullnamepopulated(whiteplayername, firstnamewhite, blackplayername, firstnameblack, isformvalid) {
if ((whiteplayername === "" || whiteplayername === null) && (firstnamewhite.trim() === "")) {
return false;
}
else if ((blackplayername === "" || blackplayername === null) && (firstnameblack.trim() === "")) {
return false;
}
return true;
};
</script>
<body style="background-color:rgb(68, 57, 57);">
<div class="warning">
<p id="warningtext"></p><br>
</div>
<div class="topnav">
<a th:href="#{main.html}"><i class="material-icons"
style="border:2px;font-size:60px;color:rgb(0, 0, 0);">arrow_back</i></a>
</div>
<div class="formformat">
<form th:object="${game}" th:action="#{/addgame}" th:method="post">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<th:block th:each="name : ${names}">
<option th:value="${name.name}"
th:text="${name.name}"></option>
</th:block>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<table>
<tr>
<th>Move</th>
<th>White</th>
<th>Black</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="white1" th:field="*{moves}"></td>
<td><input type="text" id="black1" th:field="*{moves}"></td>
</tr>
</table>
<input type="submit" value="Submit" id="submit-button">
</form>
</div>
<br><br>
</body>
</html>
Here's a solution that should meet all your requirements:
<script type="module">
const form = document.getElementById("form");
const submitButton = document.getElementById("submitbutton");
const whitePlayerName = document.getElementById("whiteplayername");
const blackPlayerName = document.getElementById("blackplayername");
const firstNameBlack = document.getElementById("firstnameblack");
const firstNameWhite = document.getElementById("firstnamewhite");
const lastNameWhite = document.getElementById("lastnamewhite");
const lastNameBlack = document.getElementById("lastnameblack");
form.addEventListener('change', () => {
const whiteNameSelected = whitePlayerName.value;
// Disable white name inputs if white name is selected in the dropdown
firstNameWhite.disabled = whiteNameSelected;
lastNameWhite.disabled = whiteNameSelected;
// Determine if the white name is either selected or typed in the inputs
const validWhiteName = whiteNameSelected || (firstNameWhite.value && lastNameWhite.value);
const blackNameSelected = blackPlayerName.value;
// Disable black name inputs if black name is selected in the dropdown
firstNameBlack.disabled = blackNameSelected;
lastNameBlack.disabled = blackNameSelected;
// Determine if the black name is either selected or typed in the inputs
const validBlackName = blackNameSelected || (firstNameBlack.value && lastNameBlack.value);
const submitAvailable = validWhiteName && validBlackName;
submitButton.disabled = !submitAvailable;
});
</script>
<form th:object="${game}" th:action="#{/addgame}" th:method="post" id="form">
<label for="whiteplayername">Select white player:</label>
<select name="whiteplayername" id="whiteplayername" th:object="${names}" th:field="${game.whitePlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select>
<label for="blackplayername">Select black player:</label>
<select name="blackplayername" id="blackplayername" th:object="${names}" th:field="${game.blackPlayerName}">
<option th:value="null" th:selected="${game.name == null}"></option>
<option value="name1">Name 1</option>
<option value="name2">Name 2</option>
</select><br><br>
<label for="firstnamewhite">First name white:</label>
<input type="text" id="firstnamewhite" th:field="*{firstNameWhite}"/>
<label for="firstnameblack">First name black:</label>
<input type="text" id="firstnameblack" th:field="*{firstNameBlack}"/><br><br>
<label for="lastnamewhite">Last name white:</label>
<input type="text" id="lastnamewhite" th:field="*{lastNameWhite}"/>
<label for="lastnameblack">Last name black:</label>
<input type="text" id="lastnameblack" th:field="*{lastNameBlack}"/><br><br>
<label for="date">Date:</label><br>
<input type="date" id="date" th:field="*{date}">
<button id="submitbutton" disabled>Submit</button>
</form>
It works by combining all the logic into a single handler for the entire form change. Then, if a name is selected in the dropdown, it disables the custom name fields, if not, it leaves them enabled. The code checks to make sure both white and black name are valid and depending on that sets the submit button enabled/disabled state.
You didn't post your whole HTML so I added the button by hand and also your selects are populated dynamically so I had to hardcode some options in them. Please, for Stack Overflow questions, always post examples reproducible by other people to aid them in helping you.
Can you provide the html code too? I also recommend to name properly ur variables and fucntions beacuase are pretty illegibles by the way. Try to type the first letter of each word that compunds the varibale in uppercase at least.
Instead of:
let firstnameblack
Do:
let firstNameBlack
I also recommend to put 2 or 3 letters according to what specifies this varibale, for example if it's a button, do:
let btnFirstNameBlack
Anyways if you can provide the html code maybe I can help you with the button issue.

How to convert one HTML Page into one PDF with Multiple Pages using Javascript

I am trying to create form with Inputs (majorly expandable textarea). I have created a button with id "create_pdf" when clicked it will generated the whole HTML into one PDF however When I click on the generate PDF button designed to run this code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Incident Report</title>
<!-- CSS -->
<style>
.myForm {
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size: 0.8em;
width: 45em;
padding: 1em;
border: 1px solid #ccc;
}
.myForm * {
box-sizing: border-box;
}
.myForm fieldset {
background-color: #eeeeee;
}
.myForm legend
{
background-color: gray;
color: white;
padding: 5px 10px;
}
.myForm label {
padding: 0;
font-weight: bold;
}
.myForm label.choice {
font-size: 0.9em;
font-weight: normal;
}
.myForm input[type="text"],
.myForm input[type="tel"],
.myForm input[type="email"],
.myForm input[type="datetime-local"],
.myForm select,
.myForm textarea {
float: right;
width: 60%;
border: 1px solid #ccc;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size: 0.9em;
padding: 0.3em;
}
.myForm textarea {
height: 50px;
width: 550px
}
.myForm button {
padding: 1em;
border-radius: 0.5em;
background: #eee;
border: none;
font-weight: bold;
margin-left: 40%;
margin-top: 1.8em;
}
.myForm button:hover {
background: #ccc;
cursor: pointer;
}
#autoresizing {
display: block;
overflow: hidden;
resize: none;
}
</style>
<script src="jquery-1.12.4.min.js"></script>
<script src="jspdf.min.js"></script>
</head>
<body>
<input type="button" id="create_pdf" value="Generate PDF">
<form class="myForm" method="get" enctype="application/x-www-form-urlencoded" action="/html/codes/html_form_handler.cfm">
<h2>Incident Report</h2>
<fieldset>
<legend>Incident Metrics</legend>
<p><label>Customer Name <input type="text" name="customer_name" required> </label></p>
<p><label>Case <input type="text" name="case" required> </label></p>
<p>
<label>Severity
<select id="Severity" name="Severity">
<option value="" selected="selected">Select One</option>
<option value="Critical" >Critical</option>
<option value="High" >High</option>
</select>
</label>
</p>
<p><label>Incident Reported Time<input type="datetime-local" name="Incident_reported_Time" required></label></p>
<p><label>Incident Resolved Time<input type="datetime-local" name="Incident_resolved_Time" required></label></p>
<p><label>MTTR<input type="text" name="MTTR" required> </label></p>
<p>
<label>SLA Achieved
<select id="SLA" name="SLA">
<option value="" selected="selected">Select One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</label>
</p>
<p>
<label>Product
<select id="Product" name="Product">
<option value="" selected="selected">Select One</option>
<option value="Command Center">Command Center</option>
<option value="ALM">ALM</option>
<option value="AGA">AGA</option>
</select>
</label>
</p>
<p><label>Teams Involved</label></p>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox4" value = "option1"> L2
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox5" value = "option2"> L3
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox6" value = "option3"> Network
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox6" value = "option3"> SysAdmin
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox6" value = "option3"> DBA
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox6" value = "option3"> Others(Please Mention)
</label>
<textarea id="textarea6">List Other Teams Involved</textarea>
</fieldset>
<br>
<fieldset>
<legend>Problem Statement</legend>
<p><label>Description</label></p>
<textarea id="autoresizing">Add Description</textarea>
<br>
<p><label>Business Impact</label></p>
<textarea id="autoResizing">Add Business Impact</textarea>
</fieldset>
<br>
<fieldset>
<legend>Workaround/Corrective Measures</legend>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox1" value = "option1"> Manual WO
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Patch
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox3" value = "option3"> N/A
</label>
</fieldset>
<br>
<fieldset>
<legend>Investigation Done</legend>
<textarea id="textarea3">Add Investigation Done</textarea>
</fieldset>
<br>
<fieldset>
<legend>Preventive Analysis</legend>
<textarea id="textarea4">Add Preventive Analysis</textarea>
</fieldset>
<br>
<fieldset>
<legend>Root Cause Analysis</legend>
<textarea id="textarea5">Add Root Cause Analysis</textarea>
</fieldset>
<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;">Upload Image</label></p>
<p><img id="output" width="500" /></p>
</form>
<script>
(function () {
var
form = $('.myForm'),
cache_width = form.width(),
a4 = [595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click', function () {
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF() {
getCanvas().then(function (canvas) {
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.addImage(img, 'JPEG', 20, 20);
doc.save('Incident_Report.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas() {
form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
return html2canvas(form, {
imageTimeout: 2000,
removeContainer: true
});
}
}());
</script>
<script>
/*
* jQuery helper plugin for examples and tests
*/
(function ($) {
$.fn.html2canvas = function (options) {
var date = new Date(),
$message = null,
timeoutTimer = false,
timer = date.getTime();
html2canvas.logging = options && options.logging;
html2canvas.Preload(this[0], $.extend({
complete: function (images) {
var queue = html2canvas.Parse(this[0], images, options),
$canvas = $(html2canvas.Renderer(queue, options)),
finishTime = new Date();
$canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
$canvas.siblings().toggle();
$(window).click(function () {
if (!$canvas.is(':visible')) {
$canvas.toggle().siblings().toggle();
throwMessage("Canvas Render visible");
} else {
$canvas.siblings().toggle();
$canvas.toggle();
throwMessage("Canvas Render hidden");
}
});
throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
}
}, options));
function throwMessage(msg, duration) {
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function () {
$message.fadeOut(function () {
$message.remove();
});
}, duration || 2000);
if ($message)
$message.remove();
$message = $('<div ></div>').html(msg).css({
margin: 0,
padding: 10,
background: "#000",
opacity: 0.7,
position: "fixed",
top: 10,
right: 10,
fontFamily: 'Tahoma',
color: '#fff',
fontSize: 12,
borderRadius: 12,
width: 'auto',
height: 'auto',
textAlign: 'center',
textDecoration: 'none'
}).hide().fadeIn().appendTo('body');
}
};
})(jQuery);
</script>
<script type="text/javascript">
var textarea = document.querySelectorAll("#autoResizing,#autoresizing,#textarea3,#textarea4,#textarea5,#textarea6");
for (var i = 0; i < textarea.length; i++){
textarea[i].addEventListener('input', autoResize, false);
}
function autoResize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
</script>
<script>
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
</body>
</html>
It only generates one Page of the whole form as PDF, Basically it is discarding everything beyond that. Can someone help me in correcting this ?

How to fix: adlistener for radio button for if else calculation

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)

form enable by input radio id (checked)

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>

How to limit checkbox selection to one using jquery or javascript

How to limit checkbox selection to one using jquery or javascript and other checkbox should be disabled after one checkbox selected?
<input type="checkbox" name="size[]" id="size" value="Small" />Small
<input type="checkbox" name="size[]" id="size" value="Medium" />Medium
<input type="checkbox" name="size[]" id="size" value="Large" />Large
<input type="checkbox" name="size[]" id="size" value="Xl" />XL
Here The Example But I Want Same Thing In Html Or Php
http://gravitywiz.com/demos/limit-how-many-checkboxes-can-be-checked/
Problem Is Solved Now Here The Final Solution
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$('input:checkbox').click(function(){
var $inputs = $('input:checkbox')
if($(this).is(':checked')){
$inputs.not(this).prop('disabled',true);
}else{
$inputs.prop('disabled',false);
}
})
})
</script>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox" />
$("input[type='checkbox']").on("click" , function(){
$("input[type='checkbox']").not(this).attr("disabled", "disabled");
});
Working Example
If you disable, user can't change his choice after first selection.
Here is a radio button behavior for checkbox.
$("input[type=checkbox]").on('click', function() {
$("input[type=checkbox]").not(this).attr('checked', false);
});
http://jsfiddle.net/BxF4Y/
But to doing that, the best way is to use radio buttons.
Browsing the source code of that page reveals the jQuery they used to achieve that effect. You should just be able to change the checkboxLimit to 1.
<script type="text/javascript">
jQuery(document).ready(function($) {
$.fn.checkboxLimit = function(n) {
var checkboxes = this;
this.toggleDisable = function() {
// if we have reached or exceeded the limit, disable all other checkboxes
if(this.filter(':checked').length >= n) {
var unchecked = this.not(':checked');
unchecked.prop('disabled', true);
}
// if we are below the limit, make sure all checkboxes are available
else {
this.prop('disabled', false);
}
}
// when form is rendered, toggle disable
checkboxes.bind('gform_post_render', checkboxes.toggleDisable());
// when checkbox is clicked, toggle disable
checkboxes.click(function(event) {
checkboxes.toggleDisable();
// if we are equal to or below the limit, the field should be checked
return checkboxes.filter(':checked').length <= n;
});
}
$("#field_11_1 .gfield_checkbox input:checkbox").checkboxLimit(3);
});
</script>
Yes, this is an old thread, however there is no real conclusion here. I have included a fiddle with my version of how check-boxes should work should you wish to limit the number of boxes checked by the user.
/** Begin HTML **/
<div class="cContainer">
<div class="cDropdown">
<div class="downArrow"></div>
<h4>Night Life</h4>
</div>
<div class="multiCheckboxes stick">
<input id="1" class="stick" type="checkbox" value="1" name="l-28">
<label class="stick" for="1">Dive Bar</label>
<br>
<input id="2" class="stick" type="checkbox" value="2" name="l-28">
<label class="stick" for="2">Pub</label>
<br>
<input id="3" class="stick" type="checkbox" value="3" name="l-28">
<label class="stick" for="3">Dance Club</label>
<br>
<input id="4" class="stick" type="checkbox" value="4" name="l-28">
<label class="stick" for="4">Pool Hall</label>
<br>
<input id="5" class="stick" type="checkbox" value="5" name="l-28">
<label class="stick" for="5">Karaoke</label>
<br>
<input id="6" class="stick" type="checkbox" value="6" name="l-28">
<label class="stick" for="6">Sports Bar</label>
<br>
<input id="7" class="stick" type="checkbox" value="7" name="l-28">
<label class="stick" for="7">Trendy</label>
<br>
</div>
/** END HTML **/
/** BEGIN JS **/
$('.cDropdown').on('click', function (e) {
$('.multiCheckboxes').slideUp(50)
e.stopPropagation();
currentDrop = $(this).next();
currentDrop.stop().slideToggle();
});
$('input:checkbox[name="l-28"]').on('change', function () {
var nightLifeLimit = $('input:checkbox[name="l-28"]:checked').length;
if (nightLifeLimit == 2) {
$('input:checkbox[name="l-28"]').each(function () {
if ($(this).is(':checked')) {
return;
}
else {
$(this).prop('disabled', true);
}
});
}
else {
$('input:checkbox[name="l-28"]').each(function () {
$(this).prop('disabled', false);
});
}
});
/** END JS **/
/** BEGIN CSS **/
.cDropdown {
background: none repeat scroll 0 0 #FFFFFF;
border: 2px inset #D3D3D3;
clear: right;
padding: 4px 3px;
width: 150px;
}
.cDropdown h4 {
font-size: 0.86em;
font-weight: normal;
margin: 0 0 0 1px;
padding: 0;
}
.downArrow {
border-left: 8px solid rgba(0, 0, 0, 0);
border-right: 8px solid rgba(0, 0, 0, 0);
border-top: 8px solid #3C3C3C;
float: right;
height: 0;
margin: 3px 0 0 3px;
width: 0;
}
.multiCheckboxes {
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #3C3C3C;
display: none;
left: 9px;
max-height: 200px;
overflow: auto;
padding: 5px;
position: absolute;
top: 35px;
width: 146px;
z-index: 999;
}
.multiCheckboxes label {
float: none !important;
font-size: 0.9em;
width: 7.6em !important;
}
http://jsfiddle.net/defmetalhead/9BYrm/1/

Categories