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>
Related
I am playing around with some code from the internet to try and create a mock dog walking appointment scheduling application. So far I have my multi-step form which works as should, however I have been trying to move on to starting the submit handling, and realised that as the 'next' button is changed to 'submit' (innerHTML), in the JavaScript, I am not sure where to put the onSubmit() handling functionality..
The challenge is that I am not allowed to use any server side programming, only HTML, CSS, JS and jQuery. Handling the form seems straight-forward enough but I am unsure where to implement the onSubmit() function.
Please go easy on me, it is a university challenge and JS is not my strong point, I have tried looking online but the only suggestions I have are for putting the onSubmit into the button itself, which would be the obvious option but as it's a multi-step form the submit button is not coded into the HTML.
https://codepen.io/caitlinmooneyx/pen/PoGqMaG
HTML
<form id="regForm" name="regForm" action="" class="col-sm-6">
<div class="tab">
<h3>Book your dog walk now</h3>
<!-- BOOKING FORM -->
<div class="row">
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<input type="text" id="fname" placeholder="First Name" name="fname" required>
<input type="text" id="lname" placeholder="Last Name" name="lname" required>
</div>
<div class="row">
<input type="number" id="number" placeholder="Contact Number" name="Number" required>
<input type="email" id="email" placeholder="Email Address" name="email">
</div>
<div class="row">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<input type="date" id="sdate" class="datepicker" name="sdate" onchange="checkStartDate()" required>
<select name="stime" id="stime" required>
<option value="" selected disabled hidden>Choose a time</option>
<option value="nine">9:00</option>
<option value="hnine">9:30</option>
<option value="ten">10:00</option>
<option value="hten">10:30</option>
<option value="eleven">11:00</option>
<option value="heleven">11:30</option>
<option value="twelve">12:00</option>
<option value="htwelve">12:30</option>
<option value="one">13:00</option>
<option value="hone">13:30</option>
<option value="two">14:00</option>
<option value="htwo">14:30</option>
<option value="three">15:00</option>
</select>
<select name="duration" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="halfhour">30 mins</option>
<option value="onehour">1 hour</option>
<option value="onehalfhour">1.5 hours</option>
<option value="twohour">2 hours</option>
</select>
</div>
<div class="row">
<p>Where should we pick up/drop off your dog?</p>
</div>
<div class="row">
<div id="locationField">
<input
id="autocomplete"
placeholder="Start typing your address..."
onFocus="geolocate()"
type="text"
required
/>
</div>
</div>
</div>
<div class="tab">
<h3>Now tell us more about your dog..</h3>
<div class="row">
<input type="text" id="dogname" placeholder="Dog Name" name="dogname" required>
</div>
<div class="row">
<p>What breed are they?</p>
</div>
<div class="row">
<select class="breeds"></select>
</div>
<div class="row">
<p>Their favourite places?</p>
</div>
<div class="row">
<input type="checkbox" id="parks" name="parks" value="Parks">
<label for="parks"> Parks</label><br>
<input type="checkbox" id="forests" name="forests" value="Forests">
<label for="forests"> Forests</label><br>
<input type="checkbox" id="beaches" name="beaches" value="Beaches">
<label for="beaches"> Beaches</label>
</div>
<div class="row">
<p>Anything else we should know? (Favourite toys, places to avoid etc)</p>
</div>
<div class="row">
<textarea></textarea>
</div>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
</div>
</form>
CSS
form p {
margin: 1em 0 .5em 1em;
}
form {
background-color: #fafafa;
padding: 1.5em;
/*margin-right: 6em;*/
}
input, select, textarea {
margin: 1em;
padding: .5em;
width: 45%;
font-size: 17px;
border: 1px solid #aaa;
}
input[type="checkbox"] {
width: auto;
margin: .5em 1em 0 1em;
}
input[type="date"] {
color: #aaa!important;
}
#locationField > input {
width: 290%!important;
}
input.invalid {
background-color: #ffdddd;
}
.tab {
display: none;
}
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
background-color: #fac123;
}
JS
// ~~~ tab functionality
var currentTab = 0; // current tab is set to be the first tab (0)
showTab(currentTab); // display the current tab
function showTab(n) {
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
fixStepIndicator(n)
}
function nextPrev(n) {
var x = document.getElementsByClassName("tab");
if (n == 1 && !validateForm()) return false;
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
showTab(currentTab);
}
function validateForm() {
var x, y, i, s, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
s = x[currentTab].getElementsByTagName("select");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += " invalid";
valid = false;
}
}
for (i = 0; i < s.length; i++) {
if (s[i].value == "") {
s[i].className += " invalid";
valid = false;
}
}
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
x[n].className += " active";
}
// ~~~ dog breed selector
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
const select = document.querySelector('.breeds');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
// ~~~ basic form validation
// ~~~ date validation
function checkStartDate() {
var startDate = document.getElementById('sdate').value;
var selectedStartDate = new Date(startDate);
var now = new Date();
if (selectedStartDate < now) {
alert("Start date must be in the future");
$("#sdate").addClass("invalid");
}
}
One solution could be to have a submit button that you hide by default (on the first tab) and show once you go to the second (or last if you add more). This way you won't have to change the innerHTML on any element and just toggle a class. Something like that could look like:
<form id="regForm" name="regForm" action="[NEED ACTION]" class="col-sm-6">
...
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" click="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
<submit type="submit" class="hide" value="Submit" />
</div>
</div>
</form>
function showTab(n) {
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").classList.add('hide');
document.getElementById("submitBtn").classList.remove('hide');
} else {
document.getElementById("nextBtn").classList.remove('hide');
document.getElementById("submitBtn").classList.add('hide');
}
fixStepIndicator(n)
}
For this to work you will need to fill in the action property for the form.
Another way you could do this without adding an extra element would be to change the onClick action for the next/submit button.
function showTab(n) {
var x = document.getElementsByClassName("tab");
var nextSubmitBtn = document.getElementById("nextBtn");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
nextSubmitBtn.textContent = "Submit";
nextSubmitBtn.onClick = someSubmitFunc;
} else {
nextSubmitBtn.textContent = "Next";
nextSubmitBtn.onClick = function () { nextPrev(1); };
}
fixStepIndicator(n)
}
This would allow you to keep the same HTML and handle the solution via JS. If you do this remember to keep the current onClick property on the "next" button as that will be the initial function ran (when you first click "next")
A couple tips and notes:
If you are only changing the text of an element (like from "next" to "submit") it would be best to use a function that only changes the text:
// Pure JS
element.textContnet = 'some text';
// jQuery
$element.text('some other text');
this will help prevent possible bugs (and potentially security risk) that can come from innerHTML.
You say you are using jQuery but it is only used in one line in the JS code presented. If that is the only line using jQuery library you could easily replace it and not include the library saving on you site size.
// jQuery way to add class (line 111)
$("#sdate").addClass("invalid");
// Pure JS equivalent
document.getElementById('sdate').classList.add('invalid');
Both will get the job done (add a class) and if you prefer to use jQuery more power to you but if that is the only place you use it then this could be an alternative.
i wrote code this i want to disable the input after check box has checked .it's OK i did that.another function is about when i click the input after that the check box has to disable .
my problem is if i want to click on check box then the check box enable after that .
this my code ;
function clickcity() {
var checkBox = document.getElementById("city-new-ad");
var myinput = document.getElementById("select-city-ad");
if (document.getElementById("city-new-ad").disabled == true) {
document.getElementById("select-city-ad").disabled == true;
}
if (document.getElementById("city-new-ad").disabled == false) {
if (checkBox.checked == true) {
document.getElementById("select-city-ad").disabled == true;
} else {
document.getElementById("select-city-ad").disabled == false;
}
}
}
function clickphone() {
var checkBox = document.getElementById("phone-ad");
if (checkBox.checked == true) {
document.getElementById("another-phone").disabled = true;
} else {
document.getElementById("another-phone").disabled = false;
}
}
function clickcity_option() {
document.getElementById("city-new-ad").disabled = true;
}
function clickphone_option() {
document.getElementById("phone-ad").disabled = true;
}
<div class="form-group">
<label for="exampleInputPassword1">phone number:</label>
<span>my phone number</span>
<input type="checkbox" id="phone-ad" onclick="clickphone()">
<br>
<span class="my-phone-ne">another phone : </span>
<input type="text" class="form-control input-register"
onclick="clickphone_option()" id="another-phone"
style="border: 1px solid #370DFF; display: inline-block; width: 30% !important; margin-right: 5px !important;">
</div>
<div class="form-group">
<label for="exampleInputPassword1">address: </label>
<span>my town</span>
<input type="checkbox" id="city-new-ad" onclick="clickcity()">
<select class="custom-select select-search select-width"
onclick="clickcity_option()" id="select-city-ad"
style=" border: 1px solid #370DFF; width: 20%;">
<option selected
style="overflow-wrap: break-word !important; text-align: center !important;">
choose city</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
made changes in HTML added onkeyup instead of onclick
<input type="text" class="form-control input-register" onkeyup="clickphone_option(this)" id="another-phone" style=" border:1px solid #370DFF; display: inline-block; width: 30% !important ;margin-right: 5px !important;">
In js clickphone_option function added a if condition, which checks if input vale is > 0 if its > 0 it will disable checkbox and if you backspace all value of checkbox it will enable checkbox again.
function clickphone_option(a) {
if(a.value.lenght>0){
document.getElementById("phone-ad").disabled = true;
}else{
document.getElementById("phone-ad").disabled = false;
}
}
Why is my code not working? How to make a button active after selecting one of the checkboxes? And how to dynamically transfer a text from checkbox to rezBlock_1 block?
CODPEN
https://codepen.io/RJDio/pen/RwPgaaZ
document.addEventListener("DOMContentLoaded", () => {
let radioBtn = document.querySelectorAll('.radioBtn');
let activeBtn = document.querySelector('.activeBtn');
let formRadio = document.querySelector('.formRadio');
let rezBlock_1 = document.querySelector('.rezBlock_1');
function checkRadio(){
for(let i =0; i < radioBtn.length; i++){
if(radioBtn[i].hasAttribute('checked')){
activeBtn.removeAttribute('disabled');
let radioValue = radioBtn[i].innerText();
rezBlock_1.innerText(radioValue);
}
}
}
checkRadio();
});
.blockRez{
width: 200px;
height: 100px;
border:1px solid red;
}
#rezBlock_1 {
width: 150px;
height: 30px;
border:1px solid blue;
}
<div class="block1">
<form class="formRadio" action="handler.php">
<p><b>Make your choose<b></p>
<p><input class="radioBtn" name="dzen" type="radio" value="red">Red</p>
<p><input class="radioBtn" name="dzen" type="radio" value="green">Green</p>
<p><input class="radioBtn" name="dzen" type="radio" value="blue">Blue</p>
<p><button class="activeBtn" disabled value="Choose">Choose</button></p>
</form>
</div>
<div class="blockRez">
<div id="rezBlock_1"></div>
</div>
You can add an eventListener for the click event. To re-activate a button set disabled to false.
document.addEventListener("DOMContentLoaded", () => {
let inputs = document.querySelectorAll(".radioBtn");
inputs.forEach(input => input.addEventListener("click", () => {document.querySelector('.activeBtn').disabled = false;}))
});
.blockRez{
width: 200px;
height: 100px;
border:1px solid red;
}
#rezBlock_1 {
width: 150px;
height: 30px;
border:1px solid blue;
}
<div class="block1">
<form class="formRadio" action="handler.php">
<p><b>Make your choose<b></p>
<p><input class="radioBtn" name="dzen" type="radio" value="red">Red</p>
<p><input class="radioBtn" name="dzen" type="radio" value="green">Green</p>
<p><input class="radioBtn" name="dzen" type="radio" value="blue">Blue</p>
<p><button class="activeBtn" disabled value="Choose">Choose</button></p>
</form>
</div>
<div class="blockRez">
<div id="rezBlock_1"></div>
</div>
I have a popup form and I have to validate fields in this form before I close this popup, I need to use this validation with a normal button, not a submit, if the fields are emty I need to mark these on a red box and put the 'This field is empty' after. After I close the form I need to clean up data from form. How should I do this using jQuery and Javascript?
<form id="frmUsers" data-userid="">
<img id="btnClose" src="resources/img/close_window.png">
<h2 id="popupTitle"></h2>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" id="username" name="txtUsername" placeholder="Please select username" class="required"/>
<p></p>
</li>
<li>
<label for="level">Level:</label>
<input type="number" id="level" name="txtLevel" placeholder="Please select level"/>
<p></p>
</li>
<li>
<label for="registrationStatus">RegistrationStatus:</label>
<select name="txtRegistrationStatus" id="registrationStatus"
placeholder="Please select registration status">
<option value="Registered">Registered</option>
<option value="Unregistered">Unregistered</option>
</select>
<p></p>
</li>
<li>
<label for="registrationDate">RegistrationDate:</label>
<input type="text" id="registrationDate" name="txtRegistrationDate"
placeholder="Please select date"/>
<p></p>
</li>
<div class="btnZone">
<input class="btnDown" type="button" value=" " id="btnPopup" />
<input class="btnDown" type="button" value="Cancel" id="btnCancel"/>
</div>
</ul>
</form>
And my form validation function:
function validateForm() {
var txtUsername = $("#username").val();
if(txtUsername == ""){
("#username").css("border-color", "red");
}
// $(":input").each(function () {
// if ($(this).val() == "") {
// $(this).css("border-color", "red");
// // $("p").html("This field is empty");
// // $("input").val("This field is required");
// // alert($(this).attr("id") & " validate error");
// }else{
// $(this).css("border-color", "black");
// }
//
// });
}
You can use one of many popup/modal plugins, but if you want to create your own, than you should do something similar to this:
var txtUsername = $("#username");
function validateForm() {
txtUsernameValid = $.trim(txtUsername.val());
txtUsername.toggleClass('invalid-input', !txtUsernameValid);
return txtUsernameValid;
};
$('[data-popup]').each(function(i) {
var thisButton = $(this);
var toPopup = $(thisButton.data('popup'));
toPopup.wrap('<div class="popup-container"><div class="popup-content"></div></div>');
var popupContainer = toPopup.closest('.popup-container').hide();
popupContainer.find('.popup-content').append('<span class="popup-close">X</span>')
thisButton.on('click', function(e) {
e.preventDefault();
popupContainer.show();
});
popupContainer.find('.popup-close').on('click', function(e) {
popupContainer.hide();
});
popupContainer.find('#btnSave').on('click', function(e) {
/* Save your data, than reset the form */
if( validateForm() ) {
popupContainer.find('form')[0].reset();
popupContainer.hide();
};
});
popupContainer.find('#btnCancel').on('click', function(e) {
popupContainer.find('form')[0].reset();
popupContainer.hide();
});
});
body {
font-family: sans-serif;
}
.popup-container {
background: none rgba(0, 0, 0, .5);
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
text-align: center;
}
.popup-container::before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.popup-content {
position: relative;
display: inline-block;
vertical-align: middle;
background: none #fff;
padding: 10px 20px;
text-align: left;
}
form ul {
list-style: none;
padding: 0;
}
.popup-close {
display: inline-block;
padding: 4px;
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
}
.invalid-input {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-popup="#frmUsers">
Open form
</button>
<form id="frmUsers" data-userid="">
<img id="btnClose" src="resources/img/close_window.png">
<h2 id="popupTitle"></h2>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" id="username" name="txtUsername" placeholder="Please select username" class="required" />
<p></p>
</li>
<li>
<label for="level">Level:</label>
<input type="number" id="level" name="txtLevel" placeholder="Please select level" />
<p></p>
</li>
<li>
<label for="registrationStatus">RegistrationStatus:</label>
<select name="txtRegistrationStatus" id="registrationStatus" placeholder="Please select registration status">
<option value="Registered">Registered</option>
<option value="Unregistered">Unregistered</option>
</select>
<p></p>
</li>
<li>
<label for="registrationDate">RegistrationDate:</label>
<input type="text" id="registrationDate" name="txtRegistrationDate" placeholder="Please select date" />
<p></p>
</li>
<div class="btnZone">
<input class="btnDown" type="button" value="Save" id="btnSave" />
<input class="btnDown" type="button" value="Cancel" id="btnCancel" />
</div>
</ul>
</form>
It is not complicated indeed, but I never try to invent hot water, I just take one of existing plugins, as Magnific Popup.
Same code on JSFiddle.
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/