why can not my function register a text that is clicked, but must I enter it manually to calculate in total?
Namely, my idea is that by clicking on a product, it is displayed in the input field [284] of the product price, and when clicking on a checkbox option to increase the price and display it at the end of [388], the text menu can now only it is compiled if I enter a number manually in field 285. How can I do it?
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent+ " " +el.querySelector('.product__price').textContent;
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach( (checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('blur', calculateSumWithInput, false);
function calculateTotal(e) {
if(e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value ="CHF "+ sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if(value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = sum;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>
I have made 2 changes.
Changed your blur function to click
inputField.addEventListener('click', calculateSumWithInput, false);
Added click triggers in your functions
inputField.click();
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent + " " + el.querySelector('.product__price').textContent;
inputField.click();
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach((checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('click', calculateSumWithInput, false);
inputField.click();
function calculateTotal(e) {
if (e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value = "CHF " + sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if (value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = "CHF " + sum + ".–";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>
Related
I want to implement a dropdown similar to the one on Booking.com in terms of functionality (I attach a screenshot), but I am encountering some issues and I can't figure out where I'm going wrong. Do you have any suggestions?
HTML
<div class="dropdown">
<input type="text" id="droptxt" class="list" readonly placeholder="Number of guests">
<div id="content" class="content">
<div class="list">
<input type="checkbox" id="rooms" class="list" value="Choose how many rooms" />
<label for="Choose how many rooms" class="list">Choose how many rooms </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="adults" class="list" value="Choose the number of adults" />
<label for="Choose the number of adults" class="list">Choose the number of adults </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="children" class="list" value="Choose the number of children" />
<label for="Choose the number of children" class="list">Choose the number of children </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
</div>
</div>
JavaScript
const txt = document.getElementById('droptxt');
console.log(txt);
const content = document.getElementById('content');
console.log(content);
const checkboxes = document.querySelectorAll('.list input[type="checkbox"]');
const quantity = document.querySelectorAll('.list input[type="number"]');
txt.addEventListener('click', function() {
content.classList.toggle('show');
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
if (!e.target.matches('.list')) {
if (content.classList.contains('show')) content.classList.remove('show');
}
};
checkboxes.forEach(function(checkbox, index) {
checkbox.addEventListener('click', function() {
quantity[index].type = (checkbox.checked) ? 'number' : 'hidden';
calc();
});
});
quantity.forEach(function(input) {
input.addEventListener('input', calc);
});
function calc() {
let arr = [];
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
arr.push(quantity[i].value + ' x ' + checkboxes[i].value);
}
}
txt.value = arr.join(', ');
}
const quantity = document.querySelectorAll('.list input[type="number"]');
in this line you are selecting input[type="number"] but in your html there is no input which type is number. use this
const quantity = document.querySelectorAll('.list input[type="hidden"]');
it will solve your problem
I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything.
i want to make the reset button to clear user inputs?
Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong.
Please i'll appreciate if anyone can assist me with this.
<div class=" DTRloading__form" style="display: block;">
<div class="form-container">
<div class="info">
</div>
<form class="form-inline">
<div class="form-group w-5 ">
<label for="red">Red Phase:</label>
<input type="number" class="form-control formInline" id="red" style="width: 80px">
</div>
<div class="form-group">
<label for="yellow">Yellow Phase:</label>
<input type="number" class="form-control formInline" id="yellow" style="width: 80px">
</div>
<div class="form-group">
<label for="blue">Blue Phase:</label>
<input type="number" class="form-control formInline" id="blue" style="width: 80px">
</div>
<div class="form-group">
<label for="neutral">Neutral:</label>
<input type="number" class="form-control formInline" id="neutral" style="width: 80px">
</div>
</form>
<label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label>
<input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required>
<button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button>
</div>
<div class="output">
<h5 class="b-display">DTR Full Load Current is:</h5>
<div id="flA" class="form-control bill"></div>
<h5 class="b-display">The percentage Loading of this DTR is:</h5>
<div id="outputLoading" class="form-control bill"></div>
<!-- <div id="outputSum" class="form-control bill"></div>-->
<button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button>
</div>
</div>
<script>
document.getElementById("btnStart3").addEventListener('click', doCalc);
function doCalc() {
// Assign user inputs to variables
let x = parseFloat(document.querySelector("#red").value);
let y = parseFloat(document.querySelector("#yellow").value);
let z = parseFloat(document.querySelector("#blue").value);
let n = parseFloat(document.querySelector("#neutral").value);
const capacity = document.querySelector("#inputKVA");
const output2 = document.querySelector("#outputLoading");
const output3 = document.querySelector("#flA");
const start3 = document.getElementById("btnStart3");
const refresh3 = document.getElementById("btnRefresh3");
// // Call the average function
getAverage(x,y,z,n);
}
function getAverage(x,y,z,n) {
// Calculate the average
let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100);
// Display result to user
console.log(average);
outputLoading.innerHTML = average.toFixed(0) + "%";
//
}
const capacity = document.querySelector("#inputKVA");
function calculate(e) {
console.log(e);
e.preventDefault();
console.log("btnStart3 clicked");
var totalfLA = ((capacity.value * 1000) / (1.7321 * 415));
console.log(totalfLA);
flA.innerHTML = totalfLA.toFixed(1) + "A";
}
function emptyInput() {
console.log("emptied!");
outputKVA.innerHTML = "";
flA.innerHTML = "";
x.value = "";
y.value = "";
z.value = "";
n.value = "";
capacity.value = "";
output2.value = "";
output3.value = "";
}
btnStart3.addEventListener("click", calculate);
refresh3.addEventListener("click", emptyInput);
</script>
You can try in html with below button type as well.
<input type="reset" value="Reset">
If you want reset form from javascript then
document.getElementById("your-form-id").reset();
Change
1. <form class="form-inline">
2. refresh3.addEventListener("click", emptyInput);
to
1. <form class="form-inline" id="form">
2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput);
3. function emptyInput() {
document.getElementById("form").reset();
}
I'm working with HTML, JavaScript and CSS. The function objective is to create a border-radius attribute in a div element(id="surface"), and assign the value typed in inputs texts(class="chars_1") to it.
HTML
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_bl">
<input type="text" id="input_bl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
JavaScript Function
function changeSize(){
var surface = document.getElementById("surface");
var inputs = document.getElementsByClassName("chars_1");
var total = 0;
for(var x = 0; x == 3; x++){
total += Number(inputs[x].value);
}
surface.style.borderRadius = String(total)+"px";
}
First I selected both elements and assigned it to these 2 variable "surface" and "inputs". "total" being used in the "for structure" to go through every input element and select every value, and afterward convert to Number to the "total" variable.
The idea is to assign to the border-radius attribute the total variable value, which will be converted to a string so it can be recognized as a value.
Have a border
Fix the for loop for (var x = 0; x < inputs.length; x++) {
Here is an upgraded version
const changeSize = (e) => {
const tgt = e.target; // which input
if (tgt.classList.contains("chars_1")) { // ah, one of those
let total = [...document.querySelectorAll(".chars_1")].reduce(
(sum, input) => {
const val = input.value;
sum += val.trim() === "" || isNaN(val) ? 0 : +val; // only add if a number
return sum;
}, 0);
console.log(String(total) + "px")
document.getElementById("surface").style.borderRadius = String(total) + "px";
}
};
window.addEventListener("load", () => { // when page loads
document.getElementById("container").addEventListener("input", changeSize);
});
#surface {
border: 3px solid black;
}
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0">
</div>
<div class="input_wrapper " id="input_wrapper_bl ">
<input type="text" id="input_bl " class="chars_1" value="0">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
for(var x = 0; x == 3; x++)
that loop doesn't even execute,
change x==3 on x<3 or whatever you want to achive.
And I guess you must have border to change it's radious
Why i get this error?
I'm using window.onload, i don't understand ... Can you help me?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Pràctica DOM3</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
<script type="text/javascript" src="script.js"></script>
<style>
h2 {
text-align: center;
border-bottom: 1px solid black;
padding-bottom: 20px;
/*text-decoration: underline;*/
}
#ultimsEstudisCursatsLabel {
margin-top: 10px;
}
#submitFormButton {
margin: auto;
display: block;
}
#resetFormButton {
margin: auto;
display: block;
}
meter {
margin: 0 auto 1em;
width: 100%;
height: .5em;
}
meter[value="1"]::-webkit-meter-optimum-value { background: red; }
meter[value="2"]::-webkit-meter-optimum-value { background: yellow; }
meter[value="3"]::-webkit-meter-optimum-value { background: orange; }
meter[value="4"]::-webkit-meter-optimum-value { background: green; }
</style>
</head>
<body>
<div class="container">
<h2>Inscripció CF Informàtica Marianao</h2>
<br>
<form method="post" action="#" id="formulari">
<div class="form-group">
<label class="control-label col-sm-2" for="input1">Nom</label>
<div class="col-sm-10">
<input type="text" name="nom" class="form-control" id="inputNom" placeholder="Escriu el teu nom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Primer cognom</label>
<div class="col-sm-10">
<input type="text" name="primerCognom" class="form-control" id="inputCognom1" placeholder="Escriu el primer cognom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Segon cognom</label>
<div class="col-sm-10">
<input type="text" name="segonCognom" class="form-control" id="inputCognom2" placeholder="Escriu el segon cognom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Data naixament </label>
<div class="col-sm-10">
<input type="date" name="dataNaixement" class="form-control" id="inputNaixament" placeholder="Selecciona la teva data de naixament ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Email </label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" id="inputEmail" placeholder="Escriu el teu correu electrònic ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Telèfon</label>
<div class="col-sm-10">
<input type="tel" name="telefon" class="form-control" id="inputTelefon" placeholder="Escriu el teu telèfon ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">DNI</label>
<div class="col-sm-10">
<input type="text" name="dni" class="form-control" id="inputDni" placeholder="Escriu el teu DNI ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="form-label col-sm-2">Cicle formatiu</label>
<div class="col-sm-10">
<select class="form-control" name="cicleFormatiu">
<option value="smx">SMX: Sistemes Microinformàtics i Xarxes</option>
<option value="asix">ASIX: Administració de Sistemes Informàtics en Xarxa</option>
<option value="dam">DAM: Desenvolupament d'Aplicacions Multiplataforma</option>
<option value="daw">DAW: Desenvolupament d'Aplicacions Web</option>
</select>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" id="ultimsEstudisCursatsLabel">Últims estudis cursats</label>
<div class="col-sm-10">
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="eso" class="custom-control-input">ESO</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="batx" class="custom-control-input">Batxillerat</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="cfgm" class="custom-control-input">CF Grau Mitjà</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="cfgs">CF Grau Superior</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="altres">Altres</label><br><br>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Usuari</label>
<div class="col-sm-10">
<input class="form-control" type="text" id="inputUsuari" name="usuari" />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Contrasenya</label>
<div class="col-sm-10">
<input type="password" id="password" name="contrasenya" class="form-control" />
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text"></p>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Torna a escriure la contrasenya</label>
<div class="col-sm-10">
<input type="password" name="contrasenyaCheck" id="contrasenyaCheck" class="form-control" disabled/>
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text"></p>
<br />
</div>
<br />
</div>
<div class="form-group">
<label class="control-label col-sm-2">Observacions</label>
<div class="col-sm-10">
<textarea class="form-control" name="observacions" id="textarea" maxlength="500"></textarea>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Termes i condicions</label>
<div class="col-sm-10">
<label class="checkbox-inline"><input type="checkbox" name="termesCondicions" value="yes" class="form-check-input" >Consulta <span>aquí</span> els termes i condicions.<br></label>
<br />
<br />
<br />
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit Form" class="btn btn-success" id="submitFormButton">
</div>
<div class="form-group">
<input type="reset" value="Reset Form" class="btn btn-primary" id="resetFormButton">
</div>
</form>
</div>
</body>
</html>
JS:
function main (){
var inputNom = document.getElementById("inputNom").addEventListener("blur", validarNomCognoms);
var inputCognom1 = document.getElementById("inputCognom1").addEventListener("blur", validarNomCognoms);
var inputCognom2 = document.getElementById("inputCognom2").addEventListener("blur", validarNomCognoms);
var inputNaixament = document.getElementById("inputNaixament").addEventListener("blur", validarData);
var inputEmail = document.getElementById("inputEmail").addEventListener("blur", validarEmail);
var inputTelefon = document.getElementById("inputTelefon").addEventListener("blur", validarTelefon);
var inputDni = document.getElementById("inputDni").addEventListener("blur", validarDni);
var inputUsuari = document.getElementById("inputUsuari").addEventListener("blur", validarUsuari);
var password = document.getElementById("password").addEventListener("blur", validaContrassenya);
// Recuento de carácteres en el text area.
var textAreaID = document.getElementById("textarea");
var length = textAreaID.getAttribute("maxlength");
var textAreaCount = document.getElementById("count");
textAreaCount.innerHTML = length + " caràcters restants.";
textAreaID.addEventListener ("keypress", function () {
document.getElementById("count").innerHTML = (length - this.value.length) + " caràcters restants.";
});
// Barra de seguridad METER.
document.addEventListener("keydown", function () {
var strength = {
0: "Molt feble.",
1: "Feble.",
2: "Acceptable.",
3: "Forta.",
4: "Molt forta."
}
var password = document.getElementById('password');
var meter = document.getElementById('password-strength-meter');
var text = document.getElementById('password-strength-text');
password.addEventListener('input', function() {
var val = password.value;
var result = zxcvbn(val);
meter.value = result.score;
if(val !== "") {
text.innerHTML = "<strong>" + strength[result.score] + "</strong>";
}
else {
text.innerHTML = "";
}
if (meter.value >= 2) {
document.getElementById("contrasenyaCheck").disabled = false;
}
else {
document.getElementById("contrasenyaCheck").disabled = true;
document.getElementById('contrasenyaCheck').value = "";
}
});
});
// VALIDACIONES.
// Primera validación.
function validarNomCognoms () {
var pattern = /^[a-zA-Z]*$/;
if (this.value.length > 0) {
if(!this.value.match(pattern)) {
this.setCustomValidity("No pot contindre números!");
this.reportValidity();
}
else {
this.setCustomValidity("");
}
}
else {
this.setCustomValidity("No pot citear buit ");
this.reportValidity();
}
}
// Segunda validación.
function validarData () {
if (this.value != "") {
var dataRecibida = this.value;
dataRecibida = dataRecibida.split("-").reverse().join("-");
// Obtener la fecha actual.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '/' + mm + '/' + yyyy;
if (dataRecibida > today) {
alert ("Data incorrecta.");
}
//this.value.setCustomValidity("");
}
else {
alert ("citeá vacío.");
}
}
// Tercera validación.
function validarEmail () {
if (this.value != "") {
var emailPattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (emailPattern.test(this.value)) {
return;
}
else {
alert ("Mail incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Cuarta validación.
function validarTelefon () {
if (this.value != "") {
var emailPattern = /^\d{9}$/;
if (emailPattern.test(this.value)) {
return;
}
else {
alert ("Telèfon incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Quinta validación.
function validarDni () {
if (this.value != "") {
var emailPattern = /^\d{8}[A-Z]$/;
if (emailPattern.test(this.value)) {
var lletres = ['T', 'R', 'W', 'A',
'G', 'M', 'Y', 'F',
'P', 'D', 'X', 'B',
'N', 'J', 'Z', 'S',
'Q', 'V', 'H', 'L',
'C', 'K', 'E', 'T'];
var index = this.value % 23;
var my_array = this.value;
var last_element = my_array[my_array.length - 1];
var boolean = false;
for (var i = 0; i < lletres.length; i++) {
if (last_element == lletres[i]) {
boolean = true;
}
}
if (boolean) {
return;
}
else {
alert ("Lletra DNI incorrecte.");
}
}
else {
alert ("DNI incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Sexta validación.
function validarUsuari () {
if (this.value != "") {
if (this.value.length < 5) {
alert ("Longitud mínima de 5 caràcters.");
}
else if (this.value.length > 12) {
alert ("Longitud màxima de 12 caràcters.");
}
else {
return;
}
}
else {
alert ("Está vacío.");
}
}
// Seéptima validación.
function validaContrassenya () {
var meter = document.getElementById('password-strength-meter');
if (meter.value < 2) {
document.getElementById("cite9").style.display = "block";
}
else {
document.getElementById("cite9").style.display = "none";
}
}
}
window.onload = main;
Thanks guys!!
ERROR:
You never defined an element with id="count". Just check.
Also, when you define it, make sure it is a direct child of the body. You may try not to do this, but sometimes errors are caused.
Hope you understand now!
Newbie on JS and got really stuck.
I have a plus and a minus button that adds up products. But I need that the result of this total price to adds up accordingly. And some of the products can only be bought with multiples of 2, 5 or 10.
I have here my html with 2 of my products. One that can only be sold with multiples of 5 and the other, multiple of 10.
<!-- Product #6 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="intem-6.jpg" alt="" />
</div>
<div class="description">
<span>DLT-19 Heavy Blaster Rifle</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" />
</button>
</div>
<div id="multiple5" class="total-price">$5800</div>
</div>
<!-- Product #7 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-7.jpg" alt="" >
</div>
<div class="description">
<span>DL-44 Heavy Blaster Pistol</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" />
</button>
</div>
<div id="multiple10" class="total-price">$1500</div>
</div>
</div>
And here is my jQuery that adds up 1 on.click of my buttons.
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value >= 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value =100;
}
$input.val(value);
});
I tried doing separately along with my searches but couldn't implement this on my other code. Just want the result to add up and decrease the price along with the on.click event of my buttons.
<html>
<head>
<title>Hello</title>
<style>
*{
font-size: 25px;
}
</style>
</head>
<body>
<button id="plus"> + </button>
<input id="quantity" type="number" value='1'>
<button id="minus"> - </button>
<div id="total">5</div>
<script>
let plus = document.getElementById('plus');
let quantityEle = document.getElementById('quantity');
let minus = document.getElementById('minus');
let total = document.getElementById('total');
let quantity = quantityEle.value;
let price = 5;
plus.addEventListener('click', function(){
quantity++;
quantityEle.value = quantity;
total.innerHTML = price * quantity;
});
minus.addEventListener('click', function(){
if(quantity > 1)
quantity--;
quantityEle.value = quantity;
total.innerHTML = price * quantity;
});
quantityEle.addEventListener('change', function(){
quantity = quantityEle.value;
total.innerHTML = price * quantity;
});
var total = $this.closest('div').find('div');
</script>
</body>
</html>
Here you go!
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $parent = $(this).closest('.item');
var $input = $parent.find('input');
var $total = $parent.find('.total-price span');
var value = parseInt($input.val());
if (value >= 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
$total.html(value);
calcTotal();
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $parent = $(this).closest('.item');
var $input = $parent.find('input');
var $total = $parent.find('.total-price span');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value = 100;
}
$input.val(value);
$total.html(value);
calcTotal();
});
function calcTotal() {
let total = 0;
$(".total-price span").each(function() {
total += parseInt($(this).html());
});
$('#total').html('$' + total);
}
#total {
color: red;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Product #6 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="intem-6.jpg" alt="" />
</div>
<div class="description">
<span>DLT-19 Heavy Blaster Rifle</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" /> +
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" /> -
</button>
</div>
<div id="multiple5" class="total-price">$<span>1</span></div>
</div>
<!-- Product #7 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-7.jpg" alt="">
</div>
<div class="description">
<span>DL-44 Heavy Blaster Pistol</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" /> +
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" /> -
</button>
</div>
<div id="multiple10" class="total-price">$<span>1</span></div>
</div>
<div>
Total: <span id="total">$2</span>
</div>
I think your question is really badly asked.
From what I understand, you seek to write an equivalence of jQuery in JS 'vanila' to increment decrement of (2, 5, 10) quantities and realize the corresponding totals.
so here is "my solution":
document
.querySelectorAll('button.minus')
.forEach(bt=>
{
bt.onclick=e=>
{
let P_parent = e.target.parentNode
, Inc = parseInt(P_parent.dataset.increment)
, U_price = parseFloat(P_parent.dataset.price).toFixed(2)
, val = parseInt(P_parent.querySelector('.quantity').value)
if (val > 0)
{
val -= Inc
P_parent.querySelector('.quantity').value = val
P_parent.querySelector('.total').textContent = '$ '+ (val * U_price).toFixed(2)
}
}
})
document
.querySelectorAll('button.plus')
.forEach(bt=>
{
bt.onclick=e=>
{
let P_parent = e.target.parentNode
, Inc = parseInt(P_parent.dataset.increment)
, U_price = parseFloat(P_parent.dataset.price).toFixed(2)
, Max = parseInt(P_parent.dataset.max)
, val = parseInt(P_parent.querySelector('.quantity').value)
if (val < Max)
{
val += Inc
P_parent.querySelector('.quantity').value = val
P_parent.querySelector('.total').textContent = '$ '+ (val * U_price).toFixed(2)
}
}
})
body { font: 14px sans-serif; padding: 1em; }
h3 { margin: 1.5em 0 0 0; }
input.quantity { width:4em; text-align: right }
.total { display: inline-block; width: 6em; text-align: right; font-weight: bold; border-bottom: 1px solid grey; margin-left: .5em }
p > button { font-weight: bold; }
<h3>by 2</h3>
<p data-increment="2" data-max=50 data-price="11">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $11
<span class="total">$ 0</span>
</p>
<h3>by 5</h3>
<p data-increment="5" data-max=80 data-price="5.23">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $5.23
<span class="total">$ 0</span>
</p>
<h3>by 10</h3>
<p data-increment="10" data-max=100 data-price="3.12">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $3.12
<span class="total">$ 0</span>
</p>