calculator does not work properly on mobile devices - javascript

I've been trying to solve this for hours and I can't.
The problem is when you try to erase the numbers entered.
You have to first select the two fields and enter the dollar amount in the third field. Then enter a value in the first field.
On the computer it works normally, but on some cell phones it is not working properly.
On some iphone using safary in the latest version it works. Already on some android devices with Google no. I didn't check the browser version, but I tried it on newer and older phones. Some new ones give a problem and some don't, as well as old ones.
This code was not developed by me, it is a little old and uses a template language called Freemarker. Don't care too much about this language, it's used to get data from the form and insert it into the html code.
There's a link for you to access and test. This page contains two calculators, it is the first one that is giving problems. I'll post a print of it.
URL: https://www.smiles.com.br/p123kby0ocxqaelzcgszc9x6hsmwt59wbrftzbr5ovtgngq7cy
Print:
Code:
<#assign
moduloSimulador = simulador_cobranded_separator
itemSimulador = moduloSimulador.getChild("item_simulador_separator").getSiblings()
>
<#list itemSimulador as cur_item>
<#assign
imagemItem = cur_item.getChild("imagem_item").getData()
textoImportanteItem = cur_item.getChild("texto_importante_item").getData()
>
<div data-simulador-mod021 class="canta-mod021-simulador">
<div>
<div>
<#if imagemItem?has_content>
<img src="${imagemItem}" alt="Imagem Simulador" />
</#if>
</div>
<div>
<div class="content-input">
<label for="lblSeg">Assinante Clube Smiles</label>
<select data-mod021-assinante id="lblSeg">
<option value="">Escolha</option>
<option value="sim">Sim</option>
<option value="nao">Não</option>
</select>
</div>
</div>
<div>
<div class="content-input">
<label for="lblCart">Tipo de Cartão</label>
<select data-mod021-cartao id="lblCart">
<option value="">Escolha</option>
<option value="infinite">Infinite</option>
<option value="platinum">Platinum</option>
<option value="gold">Gold</option>
<option value="inter">Inter</option>
</select>
</div>
</div>
<div class="break-sm"></div>
<div>
<div class="content-input rs">
<label for="lblValorGasto">Valor gasto no cartão</label>
<input value="0" min="1" maxlength="12" data-mod021-valor class="style2" type="text" id="lblValorGasto" placeholder="0" />
</div>
</div>
<div>
<div class="content-input">
<label for="lblConversor">Conversor</label>
<input data-mod021-conversor readonly class="style2" type="text" id="lblConversor" placeholder="0" />
</div>
</div>
<div>
<div class="content-input rs">
<label for="lblDolar">Cotação do Dólar</label>
<input value="0" min="1" maxlength="5" data-mod021-cotacao class="style2" type="text" id="lblDolar" placeholder="0" />
</div>
</div>
<div class="sep">=</div>
<div>
<div class="content-input">
<label for="lblAcumulo">Acúmulo</label>
<input data-mod021-acumulo readonly class="style2" type="text" id="lblAcumulo" placeholder="0" />
</div>
</div>
</div>
<p class="p-jur">
${textoImportanteItem}
</p>
</div>
</#list>
<script>
(function(window) {
"use strict";
let $items = document.querySelectorAll("[data-simulador-mod021]");
if ($items.length > 0) {
for (let a = 0; a < $items.length; a++) {
engine($items[a]);
}
}
function isValidKey(key) {
if (
(key >= 49 && key <= 57) ||
(key >= 97 && key <= 105) ||
key == 8 ||
((key == 48 || key == 96) &&
milesInput.value !== '' &&
milesInput.value !== '0')
) {
return true;
}
}
//mascara de valor
function mascaraValor(valor) {
valor = valor.toString().replace(/\D/g, "");
valor = valor.toString().replace(/(\d)(\d{9})$/, "$1.$2");
valor = valor.toString().replace(/(\d)(\d{6})$/, "$1.$2");
valor = valor.toString().replace(/(\d)(\d{3})$/, "$1.$2");
return valor;
}
function getValorMoneyBr(valor) {
let value = valor
.toFixed(2)
.toString()
.split(".");
let formatFirstPart = mascaraValor(value[0]);
let formatSecondPart = "," + value[1];
let formatedValue = formatFirstPart + formatSecondPart;
return formatedValue.toString();
}
//mascara de mordas
function moeda(v) {
v = v.toString().replace(/\D/g, ""); //permite digitar apenas números
v = v.toString().replace(/[0-9]{12}/, "inválido"); //limita pra máximo 999.999.999,99
//v = v.toString().replace(/(\d{1})(\d{8})$/, "$1.$2"); //coloca ponto antes dos últimos 8 digitos
//v = v.toString().replace(/(\d{1})(\d{1,2})$/, "$1.$2"); //coloca ponto antes dos últimos 5 digitos
v = v.toString().replace(/(\d{1})(\d{1,2})$/g, "$1,$2"); //coloca virgula antes dos últimos 2 digitos
return v.toString();
}
//define o valor do conversor
function changeConversor(c, a) {
let valueConversor = "";
let cartao = c.value;
let assinante = a.value;
if (cartao && assinante) {
if (cartao === "infinite") {
if (assinante === "sim") {
valueConversor = 4;
} else {
valueConversor = 2.2;
}
} else if (cartao === "platinum") {
if (assinante === "sim") {
valueConversor = 3;
} else {
valueConversor = 2;
}
} else if (cartao === "gold") {
if (assinante === "sim") {
valueConversor = 2.5;
} else {
valueConversor = 1.5;
}
} else {
if (assinante === "sim") {
valueConversor = 2;
} else {
valueConversor = 1.35;
}
}
return valueConversor;
} else return "";
}
function engine(item) {
let assinante = item.querySelector("[data-mod021-assinante]");
let cartao = item.querySelector("[data-mod021-cartao]");
let valor = item.querySelector("[data-mod021-valor]");
let conversor = item.querySelector("[data-mod021-conversor]");
let cotacao = item.querySelector("[data-mod021-cotacao]");
let acumulo = item.querySelector("[data-mod021-acumulo]");
let conversorValor = "";
function calc() {
let nValor = valor.value.toString().replace(/(\D)/g, "");
let nCotacao = moeda(cotacao.value);
nCotacao = nCotacao.replace(",", ".");
nCotacao = parseFloat(nCotacao);
let nConversor = parseFloat(conversor.value.toString().replace(",", "."));
if (nValor <= 0 || nCotacao <= 0) {
valor.value = "";
cotacao.value = "";
acumulo.value = "";
} else {
let v = (nValor / nCotacao) * nConversor;
// acumulo.value = getValorMoneyBr(v);
acumulo.value = Math.round(v);
}
}
valor.addEventListener("keyup", function(event) {
if(!event.keyCode) return;
let v = this.value;
valor.value = mascaraValor(v);
if (valor.value && conversor.value && cotacao.value) {
calc();
}
});
cotacao.addEventListener("keyup", function() {
if(!(event.keyCode)) return;
if (valor.value && conversor.value && cotacao.value) {
calc();
}
});
cotacao.addEventListener("keyup", function() {
if(!event.keyCode) return;
let v = this.value;
cotacao.value = moeda(v);
});
//define valor conversor
if (assinante && cartao) {
cartao.addEventListener("change", function() {
conversorValor = changeConversor(cartao, assinante);
conversor.value = conversorValor.toString().replace(".", ",");
valor.value = "";
cotacao.value = "";
acumulo.value = "";
});
assinante.addEventListener("change", function() {
conversorValor = changeConversor(cartao, assinante);
conversor.value = conversorValor.toString().replace(".", ",");
valor.value = "";
cotacao.value = "";
acumulo.value = "";
});
}
}
})(window);
</script>

Related

form calculator check box for 10% extra - how to uncheck box and 10%

I've used an old adobe Dreamweaver extension called form calculator by Kaosweaver. it made a basic form calculator for me and it works by the customer stating the total number of square meters of tiles they need. The result is the total number of tiles needed for that area.
I then added a checkbox so the customer can add 10% to the total amount onclick.
However, onclick isn't the same as true and false and when the customer unchecks the checkbox it is seen as a new onclick and adds another 10% instead of removing the first 10%.
(10% is actually *1.1 in the calculation).
Can someone please tell me how I should have the code so the checkbox performs the way I intend it to work.
function MM_findObj(n, d) { //v4.01
var p, i, x;
if (!d) d = document;
if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
d = parent.frames[n.substring(p + 1)].document;
n = n.substring(0, p);
}
if (!(x = d[n]) && d.all) x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++)
x = d.forms[i][n];
for (i = 0; !x && d.layers && i < d.layers.length; i++)
x = MM_findObj(n, d.layers[i].document);
if (!x && d.getElementById) x = d.getElementById(n);
return x;
}
function KW_getVal(o) { //v1.2
var retVal = "0";
if (o.type == "select-one") {
retVal = (o.selectedIndex == -1) ?
0 : o.options[o.selectedIndex].value;
} else if (o.length > 1) {
for (var i = 0; i < o.length; i++)
if (o[i].checked) retVal = o[i].value;
} else if (o.type == "checkbox") {
retVal = (o.checked) ? o.value : 0;
} else {
retVal = Number(o.value)
}
return parseFloat(retVal);
}
function KW_calcForm() { //v1.2
var str = "",
a = KW_calcForm.arguments;
for (var i = 3; i < a.length; i++)
str += (a[i].indexOf("#") == -1) ? a[i] : KW_getVal(MM_findObj(a[i].substring(1)));
t = Math.ceil(a[1] * eval(str)) / a[1];
tS = t.toString();
if (a[2] > 0) {
tSp = tS.indexOf(".");
if (tSp == -1) tS += ".";
tSp = tS.indexOf(".");
while (tSp != (tS.length - 1 - a[2])) {
tS += "0";
tSp = tS.indexOf(".");
}
}
MM_findObj(a[0]).value = tS;
}
<h3>Tile Calculator</h3>
<form id="form1" name="form1" method="post">
<p> <label
onclick="KW_calcForm('number of tiles',1,-1,'#squaremeters','*','50')">square meters <input name="square meters" type="text" id="squaremeters"
onkeyup="KW_calcForm('number of tiles',1,-1,'#squaremeters','*','50')" />
</label>
</p>
<p>
<label>number of tiles
<input type="text" name="number of tiles" id="numberoftiles"
readonly />
</label>
</p>
<p><strong>Remember! We always recommend to add 10% extra for cuts</strong></p>
<input name="10pecent" type="checkbox" id="myCheck"
onClick="KW_calcForm('number of tiles',1,-1,'#numberoftiles','*','1.1')" value="plus10percent"> <label>add 10% extra to total.</label>
</form>
On the site a metafield {{ product.metafields.cal.sqm }} would be used instead of the number 50 but for this example Ive used the number.
function MM_findObj(n, d) { //v4.01
var p, i, x;
if (!d) d = document;
if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
d = parent.frames[n.substring(p + 1)].document;
n = n.substring(0, p);
}
if (!(x = d[n]) && d.all) x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++)
x = d.forms[i][n];
for (i = 0; !x && d.layers && i < d.layers.length; i++)
x = MM_findObj(n, d.layers[i].document);
if (!x && d.getElementById) x = d.getElementById(n);
return x;
}
function KW_getVal(o) { //v1.2
var retVal = "0";
if (o.type == "select-one") {
retVal = (o.selectedIndex == -1) ?
0 : o.options[o.selectedIndex].value;
} else if (o.length > 1) {
for (var i = 0; i < o.length; i++)
if (o[i].checked) retVal = o[i].value;
} else if (o.type == "checkbox") {
retVal = (o.checked) ? o.value : 0;
} else {
retVal = Number(o.value)
}
return parseFloat(retVal);
}
function KW_calcForm() { //v1.2
var str = "",
a = KW_calcForm.arguments;
for (var i = 3; i < a.length; i++)
str += (a[i].indexOf("#") == -1) ? a[i] :
KW_getVal(MM_findObj(a[i].substring(1)));
t = Math.ceil(a[1] * eval(str)) / a[1];
tS = t.toString();
if (a[2] > 0) {
tSp = tS.indexOf(".");
if (tSp == -1) tS += ".";
tSp = tS.indexOf(".");
while (tSp != (tS.length - 1 - a[2])) {
tS += "0";
tSp = tS.indexOf(".");
}
}
MM_findObj(a[0]).value = tS;
}
<form id="form1" name="form1" method="post">
<div class="product-form--atc-qty form-fields--qty" data-quantity- wrapper="">
<div class="form-field form-field--qty-input">
<input class="form-field-input form-field-number form-field-filled" value="" type="text" pattern="\d*" name="square meters" type="text" id="squaremeters" onkeyup="KW_calcForm('quantity',1,-1,'#square meters','*','50')" />
<label class="form-field-title">Sq metres</label>
</div>
</div>
</form>
<form>
<input name="id" value="{{ product.variants[0].id }}" type="hidden">
<div class="product-form--atc">
<div class="product-form--atc-qty form-fields--qty">
<div class="form-field form-field--qty-input">
<input class="form-field-input form-field-number form-field-filled" value="0" id="Quantity" name="quantity" type="text" pattern="\d*" onkeyup="KW_calcForm('square meters',10,-1,'#Quantity','/','50')" aria-label="{{ 'general.general.quantity' | t }}" data-quantity-input>
<label class="form-field-title">Quantity</label>
</div>
</div>
</div>
</form>
<p>

HTML/Javascript Form How do I serialize form data as JSON and displayed in a class?

Pretty straight forward.
When a user clicks "submit", I need the form serialized and the JSON data displayed in the class"debug".
How do I do this with my current Javascript?
Cannot use jQuery. Cannot edit HTML. Only pure Javascript.
Thanks!
HTML
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
JS
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
// serialize form
var data = {};
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => {
data[input.name] = input.value;
});
The shortest possible solution (pure javascript):
var form = document.querySelector('form');
var data = new FormData(form);
docs: https://developer.mozilla.org/en-US/docs/Web/API/FormData
I know this form very well as I applied for same job position.It is an interesting task. Here is your answer with pure js!
var peopleList = [];
var addButton = document.querySelector('button.add');
var submitButton = document.querySelector('button[type=submit]');
var debug = document.querySelector('pre.debug');
var mainForm = document.forms[0];
var ageFormField = mainForm.age;
var relationshipFormField = mainForm.rel;
var smokerFormField = mainForm.smoker;
var positionFormField=mainForm.position;
//Taken from https://www.inventpartners.com/open-source/free-web-software/javascript_is_int
function is_int(value) {
if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
return true;
} else {
return false;
}
}
function formIsValid() {
return ageFormField.value != '' && is_int(ageFormField.value) && relationshipFormField.selectedIndex != 0 && positionFormField.value !='';
}
function updateDebug() {
if (peopleList.length != 0) {
debug.innerText = JSON.stringify(peopleList);
debug.setAttribute('style', 'display: block');
submitButton.disabled = false;
} else {
debug.innerText = '';
debug.removeAttribute('style');
submitButton.disabled = true;
}
}
function addEventClick(event) {
event.preventDefault();
if (formIsValid()) {
peopleList.push({
'age': ageFormField.value,
'position':positionFormField.value,
'relationship': relationshipFormField.options[relationshipFormField.selectedIndex].value,
'isSmoker': smokerFormField.checked,
});
updateDebug();
ageFormField.value = '';
positionFormField.value='';
relationshipFormField.selectedIndex = 0;
smokerFormField.checked = false;
} else {
var errors = '';
if (ageFormField.value == '') {
errors += 'Please enter your age!';
} else if (!is_int(ageFormField.value)) {
errors += 'Age must be a numeric value!';
}
if (relationshipFormField.selectedIndex == 0) {
if (errors != '') {
errors += '\n';
}
errors += 'Please select your relationship status!';
}
if (positionFormField.value == '') {
if (errors != '') {
errors += '\n';
}
errors += 'Please enter your position!';
}
if (errors != '') {
alert(errors);
errors = '';
}
else if (
errors != '') {
alert(errors);
errors = '';
}
}
}
function submitEventClick(event) {
event.preventDefault();
if (peopleList.length != 0) {
var http = new XMLHttpRequest();
var url = "savePeopleList.php";
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if (http.readyState == 4) {
if (http.status == 200) {
peopleList = [];
updateDebug();
alert('All of the changes were saved to the server!');
} else {
alert('An error occured while sending the data to the server!');
}
}
};
http.send(JSON.stringify(peopleList));
}
}
addButton.addEventListener('click', addEventClick, false);
submitButton.addEventListener('click', submitEventClick, false);
updateDebug();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Position
<input type="text" name="position">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Iterate through the form, grabbing the various elements and creating new objects for each one, then setting the properties for each object and pushing to the final array would solve your problem fairly easily.
Then you can simply use querySelectorAll to match .debug and use JSON.stringify() to convert your array to a string and innerText to set the contents.
Example:
function go() {
var debug_class = document.querySelectorAll(".debug");
for (var i = 0; i < debug_class.length; i++) {
var element = debug_class[i];
element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
}
}
function serializeArray(form) {
var field, l, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (i = 0; i < len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
l = form.elements[i].options.length;
for (j = 0; j < l; j++) {
if (field.options[j].selected)
s[s.length] = {
name: field.name,
value: field.options[j].value
};
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = {
name: field.name,
value: field.value
};
}
}
}
}
return s;
}
<form id="blah">
<input type="text" name="input1" value="a"></input>
<input type="text" name="input2" value="b"></input>
<input type="text" name="input3" value="c"></input>
<input type="text" name="input4" value="d"></input>
</form>
<button onclick="go()">Serialize!</button>
<div class="debug"></div>
EDIT
In your particular case, after including the above code, you would have to call go() at some point to generate the serialized data.
Here's how to do it after clicking on add
document.querySelector(".add").onclick = function(event) {
go(); // display in .debug
event.preventDefault();
createinput()
}
FULL SNIPPET
function go() {
var debug_class = document.querySelectorAll(".debug");
for (var i = 0; i < debug_class.length; i++) {
var element = debug_class[i];
element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
}
}
function serializeArray(form) {
var field, l, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (i = 0; i < len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
l = form.elements[i].options.length;
for (j = 0; j < l; j++) {
if (field.options[j].selected)
s[s.length] = {
name: field.name,
value: field.options[j].value
};
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = {
name: field.name,
value: field.value
};
}
}
}
}
return s;
}
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
go();
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
go();
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
// serialize form
var data = {};
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => {
data[input.name] = input.value;
});
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>

HTML/Javascript Forms Checkbox Value Not Displaying

Pretty Straight forward problem.
When the user hits the "add" button and the checkmark is checked I would like the value to say "Smoker" in the class="household".
When the checkmark is not checked I would like the value to say "Non-smoker"
Currently, my "if else" statement isn't firing. Been looking everywhere to fix this. Can anyone help?
Side Note: No jQuery, Cannot edit the HTML. Only Pure Javascript.
HTML
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
JS
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].value.checked;
if( z === undefined) {
return ("Non smoker \n")
}
else {
return ("Smoker \n")
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
The first problem is you are not getting the checkbox status right way. It should be document.getElementsByName("smoker")[0].checked instead of document.getElementsByName("smoker")[0].value.checked.
The second problem is you used return in if else. If you use return then the following codes of the function will not execute.
Change
var z = document.getElementsByName("smoker")[0].value.checked;
if( z === undefined) {
return ("Non smoker \n")
}
else {
return ("Smoker \n")
}
to
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
Because you have only one "household" element you can add the following handler:
document.querySelectorAll('[name="smoker"]')[0].onclick = function() {
document.getElementsByClassName('household')[0].textContent =
this.checked ? 'Smoker' : 'Non-smoker';
}
The example:
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if( !z ) {
z = "Non smoker";
}
else {
z = "Smoker";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
document.querySelectorAll('[name="smoker"]')[0].onclick = function() {
document.getElementsByClassName('household')[0].textContent = this.checked ? 'Smoker' : 'Non-smoker'
}
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>

Issue with displaying the correct output. JS radio button selection and addition

So I have this code:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<input type="radio" id="radiobtn1" name="bubbles" onclick="CalculatePrice();"> Less Than 10 Bubbles<br />
<input type="radio" id="radiobtn2" name="bubbles" onclick="CalculatePrice();"> 10 Bubbles<br />
<input type="radio" id="radiobtn3" name="bubbles" onclick="CalculatePrice();"> More than 10 Bubbles<br />
<br />
<input type="radio" id="radiobtn4" name="hours" onclick="CalculatePrice();"> 1 Hour<br />
<input type="radio" id="radiobtn5" name="hours" onclick="CalculatePrice();"> 2 Hours<br />
<input type="radio" id="radiobtn6" name="hours" onclick="CalculatePrice();"> Any Longer<br />
<br />
<input type="checkbox" id="radiobtn7" name="bubbles" onclick="CalculatePrice();"> Inflatable Goals<br />
<input type="checkbox" id="radiobtn8" name="bubbles" onclick="CalculatePrice();"> Icey Cold Bottled Water<br />
<input type="checkbox" id="radiobtn9" name="bubbles" onclick="CalculatePrice();"> Photo and Video Package<br />
<script>
function CalculatePrice() {
var a, b;
var c = 0;
var d = 0;
var e = 0;
var price;
if($(radiobtn1).is(':checked')) {
a = 0;
// alert(a);
}
else if($(radiobtn2).is(':checked')) {
a = 1;
//alert(a);
}
else if($(radiobtn3).is(':checked')) {
a = 0;
//alert(a);
}
if($(radiobtn4).is(':checked')) {
b = 350;
//alert(b);
}
else if($(radiobtn5).is(':checked')) {
b = 450;
//alert(b);
}
else if($ (radiobtn6).is(':checked')) {
b = 0;
// alert(b);
}
if($(radiobtn7).is(':checked')) {
c = 50;
//alert(b);
}
else if($(radiobtn8).is(':checked')) {
d = 20;
//alert(b);
}
else if($ (radiobtn9).is(':checked')) {
e = 50;
// alert(b);
}
if(a == 0)
{
price = 0;
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
//alert(price);
}
else if (b == 0)
{
price = 0;
// alert(price);
}
else
{
price = b;
price = price + new Number(c) + new Number(d) + new Number(e);
if(price != undefined)
{
price = "$" + price;
//document.getElementById('output').innerHTML = '$';
document.getElementById('output').innerHTML = price;
}
else if(a == 0)
{
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
}
}
}
</script>
<br /><br />
<div id="output" style="font-weight:normal;color:#000000;letter-spacing:0pt;word-spacing:-2pt;font-size:36px;text-align:left;font-family:helvetica, sans-serif;line-height:1;"></div>
I am having trouble with the output of CalculatePrice() displaying $NaN or not adding the checkboxes. I have looked over it many times and still can't seem to work out what the issue is. I have all the checkboxes being added if they were selected but it only seems to add 1 and then not the rest. Not sure what to do!
Any help would be appreciated! Thanks.
Two things:
Change code similar to $(radiobtn1) to $("#radiobtn1"). You're referencing an id, and that's the syntax you use to do so.
Instead of calling the function from within the html, call it from the JS using jQuery's .change() function.
jQuery
$('input').change(function(){
CalculatePrice();
});
function CalculatePrice() {
var a, b;
var c = 0;
var d = 0;
var e = 0;
var price;
if ($("#radiobtn1").is(':checked')) {
a = 0;
//alert(a);
} else if ($("#radiobtn2").is(':checked')) {
a = 1;
//alert(a);
} else if ($("#radiobtn3").is(':checked')) {
a = 0;
//alert(a);
}
if ($("#radiobtn4").is(':checked')) {
b = 350;
//alert(b);
} else if ($("#radiobtn5").is(':checked')) {
b = 450;
//alert(b);
} else if ($("#radiobtn6").is(':checked')) {
b = 0;
// alert(b);
}
if ($("#radiobtn7").is(':checked')) {
c = 50;
//alert(b);
} else if ($("#radiobtn8").is(':checked')) {
d = 20;
//alert(b);
} else if ($("#radiobtn9").is(':checked')) {
e = 50;
// alert(b);
}
if (a == 0) {
price = 0;
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
//alert(price);
} else if (b == 0) {
price = 0;
// alert(price);
} else {
price = b;
price = price + new Number(c) + new Number(d) + new Number(e);
if (price != undefined) {
price = "$" + price;
//document.getElementById('output').innerHTML = '$';
document.getElementById('output').innerHTML = price;
} else if (a == 0) {
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
}
}
}
Fiddle
The math is still a little strange, so I'd check that.

How to show 0.00 when check box not checked?

How to display 0.00 in the totalcost field when check box not checked ?
<form id="form1">
<input type="checkbox" id='game0' value="9.99" onclick="UpdateCost()">Game 1 ( 9.99)<br>
<input type="checkbox" id='game1' value="19.99" onclick="UpdateCost()">Game 2 (19.99)<br>
<input type="checkbox" id='game2' value="27.50" onclick="UpdateCost()">Game 3 (27.50)<br>
<input type="checkbox" id='game3' value="45.65" onclick="UpdateCost()">Game 4 (45.65)<br>
<input type="checkbox" id='game4' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="checkbox" id='game5' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="text" id="totalcost" value="">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "";
}
}
return null;
}());
</script>
Specify default value for the input:
<input type="text" id="totalcost" value="0.00">
Set the default value to 0.00:
totalcost.value = (sum > 0) ? sum.toFixed(2) : "0.00";
DEMO
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "0.00";
}
}
return null;
}());

Categories

Resources