Im having a form with several input fields and im trying to do a js script that while i click on a button my inputs become empty and my form does not submit.
This is my form:
let btnClear = document.querySelector('button');
let inputs = document.querySelector('inputs');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = ' ');
});
let $departemento = document.getElementById('departamento')
let $provincia = document.getElementById('provincia')
let $distrito = document.getElementById('distrito')
let departamentos = ['Argentina', 'Brasil']
let provincias = ['Bs As', 'Cordoba', 'San Pablo']
let distritos = ['San Miguel', 'San Nicolas', 'Tigre', 'Belgrano', 'Calamuchita', 'La falda', 'Gral Belgrano', 'Santa Marta', 'Loa Loa']
function mostrarLugares(arreglo, lugar) {
let elementos = '<option selected disables>--Seleccione--</option>'
for(let i = 0; i < arreglo.length; i++) {
elementos += '<option value="' + arreglo[i] +'">' + arreglo[i] +'</option>'
}
lugar.innerHTML = elementos
}
mostrarLugares(departamentos, $departemento)
function recortar(array, inicio, fin, lugar) {
let recortar = array.slice(inicio, fin)
mostrarLugares(recortar, lugar)
}
$departemento.addEventListener('change', function() {
let valor = $departemento.value
switch(valor) {
case 'Argentina':
recortar(provincias, 0, 2, $provincia)
break
case 'Brasil':
recortar(provincias, 2, 3, $provincia)
break
}
$distrito.innerHTML = ''
})
$provincia.addEventListener('change', function() {
let valor = $provincia.value
if(valor == 'Bs As') {
recortar(distritos, 0, 4, $distrito)
} else if(valor == 'Cordoba') {
recortar(distritos, 4, 7, $distrito)
} else {
recortar(distritos, 7, 9, $distrito)
}
})
<div class="container">
<div class="row">
<div class="col-12">
<form method="post" action="ServletPacientes">
<h1 class="h1 mb-5" >Ingresar nuevo paciente</h1>
<div class="form-row">
<div class="form-group col-md-4">
<div>
<label>Nombre:</label>
<input type="text" onkeypress="return checkLetras(event)" class="form-control" name="txtNombre" title="Ingrese su nombre" required /> </div>
</div>
<div class="form-group col-md-4">
<div>
<label>Apellido:</label>
<input type="text" onkeypress="return checkLetras(event)" class="form-control" name="txtApellido" required="">
</div>
</div>
<div class="form-group col-md-4">
<label>DNI: </label>
<input type="text" onkeypress="return check(event)" maxlength="8" minlength="7" class="form-control" name="txtDNI" required>
</div>
<div class="form-group col-md-4">
<label>Correo electrónico: </label>
<input type="email" class="form-control" name="txtCorreo" required>
</div>
<div class="form-group col-md-4">
<label>Teléfono: </label>
<input type="text" onkeypress="return check(event)" class="form-control" name="txtTelefono" required>
</div>
<div class="form-group col-md-4">
<label>Fecha de nacimiento: </label>
<input type="date" class="form-control " name="txtFechaNac" required>
</div>
<div class="form-group col-md-4">
<label for="departamento" > Nacionalidad</label>
<select name="comboNacionalidad" id="departamento" class="form-control ">
<!-- cargaremos las etiquetas de option con javascript -->
</select>
</div>
<div class="form-group col-md-4">
<label for="provincia"> Provincias</label>
<select name="comboProvincia" id="provincia" class="form-control ">
<!-- cargaremos las etiquetas de option con javascript -->
</select>
</div>
<div class="form-group col-md-4">
<label for="distrito" > Localidades</label>
<select name="comboLocalidad" id="distrito" class="form-control ">
<!-- cargaremos las etiquetas de option con javascript -->
</select>
</div>
<div class="col-12">
<input onclick="confirmarAgregar(event)" type="submit" class="btn btn-success" value="Aceptar" name="btnAceptar">
<button type="" class="btn btn-outline-primary btnClear">Limpiar campos</button>
</div>
</div>
</form>
</div>
</div>
</div>
For some reason my form is being submitted and redirecting me to another page and my texts are never emptying. I took the submit type to my but and still does not work.
The confirmAgregar function, wherever it's defined, needs to be updated as so:
function confirmAgregar(event){
event.preventDefault()
// ... rest of your code
}
The default behavior of an HTML form submission event is to refresh the page. When you use JavaScript to handle the form submission, you usually want to prevent that behavior, then let your handle submit function perform whatever logic your form needs to do.
For preventing form submit you need to call preventDefault() on form submit event:
<form method="post" action="ServletPacientes" onsubmit="event.preventDefault()">
...
</form>
For clearing inputs you need to set correct tag name, select them all and make array to iterate them:
let inputs = [...document.querySelectorAll('input')];
Or you can just reset all your form:
const form = document.querySelector("form");
form.reset(); // reset all inputs and form elements inside this form
Related
I'm finding a strange behaviour in a popup FORM when I click on a BUTTON (that operates on some object using a JS code), and on a INPUT (used for submit): in both cases, the form closes, and it is an unexpected action.
Probably is due to something very easy and common that I'm not fixing, but i can't find it.
This is the HTML interested part:
<form name="contactform" id="contactform" class="contact-form">
<div class="contactform-container">
<div class="common">
<label for="name">Nome</label>
<input type="text" id="name" name="name" />
</div>
<div class="common">
<label for="name">Cognome</label>
<input type="text" id="familyName" name="familyName" />
</div>
<div class="common">
<label for="email">e-mail</label>
<input type="text" id="email" name="email" />
</div>
<div class="message">
<label for="message">Annotazioni</label>
<textarea name="message" id="message" class="message"></textarea>
</div>
<div class="passRow">
<fieldset class="validatePass">
<div class="formGroup">
<label class="formLabel"for="password">Password
<span class="passErr"></span>
</label>
<div class="passWrapper">
<input type="password"
id="password"
class="form-control input-md"
name="password"
placeholder="Enter your password">
<span class="showPass">
<i class="fas fa-eye-slash"></i>
</span>
</div>
<p class="progress">Livello di sicurezza</p>
<div id="progressBar">
<div></div>
</div>
<ul id="progressList">
<li>Un carattere minuscolo e uno maiuscolo</li>
<li>Un numero</li>
<li>Un carattere speciale tra "!,%,&,#,#,$,^,*,?,_,-"</li>
<li>Lunghezza minima: 8 caratteri</li>
</ul>
</div>
</fieldset>
</div>
<div class="securityCaptcha">
<p>Inserire il codice nei riquadri sottostanti</p>
<div class="first row">
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck last">
<canvas class="valiCaptcha"></canvas>
<button class="reloadButton">
<i class="fas fa-redo"></i>
</button>
</div>
</div>
<div class="second row">
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
</div>
</div>
<div class="contactArea">
<p>Compilare tutti i dati per la prenotazione.</p>
<input type="submit" name="submit" id="submit" value="send">
</div>
</div>
</form>
</div>
The BUTTON that create problem is the one with class reloadButton.
The INPUT is the one with id submit.
I think css aren't necessary.
Regarding the JS part:
let formEls = formPopup.querySelectorAll('.common, .message, .note');
let charCode = [];
const refreshButton = document.querySelectorAll('.reloadButton')[0];
const passInput = document.getElementById('password');
window.onload = function () {
document.querySelector('#reserveBtn').addEventListener('click', function () {
formPopup.classList.add('active');
});
getCode();
formPopup.querySelector('.closeButton').addEventListener('click', function () {
cleanForm();
formPopup.classList.remove('active');
});
formPopup.addEventListener('click', function (ev) {
if (ev.target.id == 'contactform-bg') {
cleanForm();
formPopup.classList.remove('active');
}
});
refreshButton.addEventListener('click', function (ev) {
charCode = [];
getCode();
});
passInput.addEventListener('keyup', function () {
passVal = passInput.value;
checkPass(passVal);
});
};
let cleanForm = function () {
formEls.forEach((item, i) => {
item.classList.remove('typing');
});
// console.log(window['contactform-bg'].innerHTML);
// console.log(document.getElementById('contactform').innerHTML);
// console.log(document.contactform.innerHTML);
document.contactform.name.value = '';
document.contactform.familyName.value = '';
document.contactform.email.value = '';
document.contactform.message.value = '';
passInput.value = '';
};
function getCode() {
let sChars = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,!,#,#,$,%,^,&,*,(,)';
let arrayChars = sChars.split(',');
for (var i = 0; i <= 3; i++) {
// trova un indice casuale tra 0 e la lunghezza dell'array
RefIndex = Math.floor(Math.random() * arrayChars.length);
// assegna il carattere estratto dall'array (strana indicazione del font come giapponese(??)
let char = arrayChars[RefIndex];
charCode[i] = char.toLowerCase;
createImgCaptcha(char, i);
}
}
I avoid to add the createImgCaptcha function because it just create CANVAS and doesn't have any impact on the matter.
Is there anyone able to explain to me why the FORM closes? I tried following the steps in JS but found no errors.
Thanks in advance.
Ok, I found the problems and fixed them.
There were little mistakes one different from another. So, I list them:
The "FORM close object": there was a missing '#' characer in the ref attribute, so I changed the HTML from to , adding also the type attribute for greater completeness.
The "class reloadButton": I finally read that a <button>Click to do something</button> is a default submit button. I didn't know... so, I just added the right type attribute to solve, in this way: <button class="reloadButton" type="button">.
The "submit button": in this case, I changed the prevent JS command: function stopEvent(event) { event.preventDefault();}.
Now, everything works correctly. Sorry if I bored you with these silly things; either way, it's always best to learn from mistakes.
In a simple form there are 3 input fields with regex pattern in each.
Two of them ('Password' and 'Confirm Password') must match. If the don't, a message "Not Matching" is displayed. If they do, "Valid" is displayed.
How can I (via the javascript) force the Bootstrap 4 validation's red border and 'X' icon to be displayed in the following case :
Entering 'aa' in the 'Password' field (it matches the regex hence the valid green border and V icon).
Entering 'aa' in the 'Confirm Password' field (it matches the regex hence the valid green border and V icon).
Now I add another character to 'Confirm Password' and it immediately displays "Not Matching", but since it's ok according to the regex - it is still green with a 'V' icon.
I need to force the red border and 'X' icon when this happens.
My code :
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red;
}
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4">
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<div class="form-group">
Field1<input type="text" class="form-control" pattern="^[a-z]{2,4}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Password<input type="text" id="pwdId" class="form-control" pattern="^[a-z]{2,4}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Confirm Password<input type="text" id="cPwdId" class="form-control" pattern="^[a-z]{2,4}$" required>
<div id="cPwdValid" class="valid-feedback">Valid</div>
<div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
// Check if passwords match
$('#pwdId, #cPwdId').on('keyup', function () {
if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val()) {
$("#submitBtn").attr("disabled",false);
$('#cPwdValid').show();
$('#cPwdInvalid').hide();
$('#cPwdValid').html('Valid').css('color', 'green');
} else {
$("#submitBtn").attr("disabled",true);
$('#cPwdValid').hide();
$('#cPwdInvalid').show();
$('#cPwdInvalid').html('Not Matching').css('color', 'red');
}
});
let currForm1 = document.getElementById('myForm1');
// Validate on submit:
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
currForm1.classList.add('was-validated');
}, false);
// Validate on input:
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
input.classList.remove('is-invalid')
input.classList.add('is-valid');
} else {
input.classList.remove('is-valid')
input.classList.add('is-invalid');
}
var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
$("#submitBtn").attr("disabled", !is_valid);
});
});
});
</script>
Thank you!
Couldn't you toggle the is-invalid class as needed on both password inputs?
$('#pwdId, #cPwdId').on('keyup', function () {
if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val()) {
$("#submitBtn").attr("disabled",false);
$('#cPwdValid').show();
$('#cPwdInvalid').hide();
$('#cPwdValid').html('Valid').css('color', 'green');
$('.pwds').removeClass('is-invalid')
} else {
$("#submitBtn").attr("disabled",true);
$('#cPwdValid').hide();
$('#cPwdInvalid').show();
$('#cPwdInvalid').html('Not Matching').css('color', 'red');
$('.pwds').addClass('is-invalid')
}
});
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<div class="form-group">
Field1<input type="text" class="form-control" pattern="^[a-z]{2,4}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Password<input type="text" id="pwdId" class="form-control pwds" pattern="^[a-z]{2,4}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Confirm Password<input type="text" id="cPwdId" class="form-control pwds" pattern="^[a-z]{2,4}$" required>
<div id="cPwdValid" class="valid-feedback">Valid</div>
<div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
</div>
</form>
Demo: https://www.codeply.com/p/AQBzIBAsZl
With help from #Zim I got started and managed to solve it.
Following is the code for a full Registration form with comparison of the 2 passwords.
Notice that the Submit button is enabled ONLY when all elements in the form are valid!
Note 1 : I tested it extensively but it might have a bug or a design flaw (please let us all know about it if you find one).
Note 2 : When it comes to Javascript and JQuery, I was born a mere 2 weeks ago, so I guess my solution is not as elegant as can possibly be (again, let us all know if you can improve it).
Here is the full code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><title>Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red;
}
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4" style="background-color: lightblue;">
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<h1 class="text-center">Registration</h1><hr>
<div class="form-group">
First Name<input name="myInput" id="fisrtNameId" type="text" class="form-control" pattern="^[a-z]{2,15}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 15 long)</div>
</div>
<div class="form-group">
Last Name<input name="myInput" id="lastNameId" type="text" class="form-control" pattern="^[a-z]{2,15}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 15 long)</div>
</div>
<div class="form-group">
E-mail<input type="email" name="myInput" id="emailId" class="form-control" pattern="^[a-zA-Z0–9.!#$%&’*+\/=?^_`{|}~-]+#[a-zA-Z0–9](?:[a-zA-Z0–9-]{0,61} [a-zA-Z0–9])?(?:\.[a-zA-Z0–9](?:[a-zA-Z0–9-]{0,61}[a-zA-Z0–9])?)*$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">Not a valid email address</div>
</div>
<div class="form-group">
Password<input type="text" id="pwdId" class="form-control" pattern="^[a-z]{2,6}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 6 long)</div>
</div>
<div class="form-group">
Confirm Password<input type="text" id="cPwdId" class="form-control myCpwdClass" pattern="^[a-z]{2,6}$" required>
<div id="cPwdValid" class="valid-feedback">Passwords Match</div>
<div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 6 long)</div>
</div>
<div class="form-group">
Description<textarea form="myForm1" name="myInput" id="descId" type="text" class="form-control" required></textarea>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">Required</div>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" id="agreeId" class="custom-control-input form-control" required>
<label for="agreeId" id="agreeLabelId" class="custom-control-label">Agree to terms (terms & conditions)</label>
<div id="agreeValid" class="valid-feedback">Valid</div>
<div id="agreeInvalid" class="invalid-feedback">Needs to be checked</div>
</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-secondary" disabled>Register</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
// ----------- Set all elements as INVALID --------------
var myInputElements = document.querySelectorAll(".form-control");
var i;
for (i = 0; i < myInputElements.length; i++) {
myInputElements[i].classList.add('is-invalid');
myInputElements[i].classList.remove('is-valid');
}
// ------------ Check passwords similarity --------------
$('#pwdId, #cPwdId').on('keyup', function () {
if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val() ) {
$('#cPwdValid').show();
$('#cPwdInvalid').hide();
$('#cPwdInvalid').html('Passwords Match').css('color', 'green');
$('.myCpwdClass').addClass('is-valid');
$('.myCpwdClass').removeClass('is-invalid');
$("#submitBtn").attr("disabled",false);
$('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
for (i = 0; i < myInputElements.length; i++) {
var myElement = document.getElementById(myInputElements[i].id);
if (myElement.classList.contains('is-invalid')) {
$("#submitBtn").attr("disabled",true);
$('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
break;
}
}
} else {
$('#cPwdValid').hide();
$('#cPwdInvalid').show();
$('#cPwdInvalid').html('Not Matching').css('color', 'red');
$('.myCpwdClass').removeClass('is-valid');
$('.myCpwdClass').addClass('is-invalid');
$("#submitBtn").attr("disabled",true);
$('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
}
});
// ----------------- Validate on submit -----------------
let currForm1 = document.getElementById('myForm1');
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
else {
$("#submitBtn").attr("disabled",false);
$('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
currForm1.classList.add('was-validated');
}
}, false);
// ----------------- Validate on input -----------------
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
input.classList.remove('is-invalid');
input.classList.add('is-valid');
} else {
input.classList.remove('is-valid');
input.classList.add('is-invalid');
}
var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
// $("#submitBtn").attr("disabled", !is_valid);
if (is_valid) {
$("#submitBtn").attr("disabled",false);
$('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
} else {
$("#submitBtn").attr("disabled",true);
$('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
}
});
});
// ------------------------------------------------------
});
</script>
</body>
</html>
I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
There are no errors in console.
UPDATE:
Using the code that colecmc provide(Thank you!!) I updated the codepen. I like how the date.now is added, but I would like to just do a an incremental increase. Im not sure how to apply that to this function I tried zer00ne's index incremental but am doing something wrong.
let cloneList = [],
index = 0; // index must be declared apart from function or else you will set it to the initial value every time the function is called.
document.getElementById('launch').onclick = function(event) {
event.preventDefault();
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
var component = clonedNode.querySelector('input');
index++;
clonedNode.id = index+1;
cloneList.push(clonedNode.id);
component.id = `componentID_${clonedNode.id}`;
component.name = `componentName_${clonedNode.id}`;
container.appendChild(clonedNode);
}
Im having an issue with my form. Initially I had two forms on the page. However on submit only the info from the first form was written. I tried combining the forms. Now if i fill out the campaign and component inputs and submit it writes to the correct tables(good!). However the component section is supposed to be replicated. A campaign can have as many components as the user wants. I am using cloneNode and before I combined the table it added more component sections. Now that they are combined the function no longer works. Im confused if this is even the right approach for what Im doing. I included a copdpen that shows a stripped down version of what Im trying to do.
Basically I want to be able to press add component, add as many new components as I'd like fill them out and have then all written as records to the db. I need a way to differentiate all the clones (new ids or names?)
codepen: https://codepen.io/anon_guy/pen/VMZWWW?editors=1010
HTML:
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-event" class="form-horizontal">
<div class="col-sm-4">
<label>name</label>
<input type="text" name="name" value="name" placeholder="name" id="name" class="form-control" />
</div>
<div class="col-sm-4">
<label>address</label>
<input type="text" name="address" value="address" placeholder="address" id="address" class="form-control" />
</div>
<div class="col-sm-4">
<label>phone</label>
<input type="text" name="phone" value="phone" placeholder="phone" id="phone" class="form-control" />
<div class="text-danger"></div>
</div>
</div>
<div class="row">
<div class="add_component">
<button id='launch'>Add Component</button>
</div>
</div>
</div>
<div class="wrapper" id="add-components">
<div class="panel panel-default " id="addon">
<div class="panel-heading">
</div>
<div class="panel-body">
<div class="col-sm-6">
<label>component</label>
<input type="text" name="component" value="component" placeholder="component" id="component" class="form-control" />
</div>
</form>
</div>
</div>
</div>
JS:
document.getElementById('launch').onclick = function() {
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
container.appendChild(clonedNode );
}
You will want to try something like this before appending to the container clonedNode.id = Date.now();
That will provide a way to differentiate all the clones by giving a unique id. You can take it a step further like this:
let cloneList = [];
document.getElementById('launch').onclick = function(event) {
event.preventDefault();
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
var component = clonedNode.querySelector('input');
clonedNode.id = Date.now();
cloneList.push(clonedNode.id);
component.id = `componentID_${clonedNode.id}`;
component.name = `componentName_${clonedNode.id}`;
container.appendChild(clonedNode);
}
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-event" class="form-horizontal">
<div class="col-sm-4">
<label>name</label>
<input type="text" name="name" value="name" placeholder="name" id="name" class="form-control" />
</div>
<div class="col-sm-4">
<label>address</label>
<input type="text" name="address" value="address" placeholder="address" id="address" class="form-control" />
</div>
<div class="col-sm-4">
<label>phone</label>
<input type="text" name="phone" value="phone" placeholder="phone" id="phone" class="form-control" />
<div class="text-danger"></div>
</div>
</div>
<div class="row">
<div class="add_component">
<button id='launch'>Add Component</button>
</div>
</div>
</div>
<div class="wrapper" id="add-components">
<div class="panel panel-default " id="addon">
<div class="panel-heading">
</div>
<div class="panel-body">
<div class="col-sm-6">
<label>component</label>
<input type="text" name="component" value="component" placeholder="component" id="component" class="form-control" />
</div>
</form>
</div>
</div>
</div>
This is the closest I came to what I believe is your way of thinking by looking at your code. (I also removed some unnecessary steps in your code to make it a little bit cleaner). This is for if you must have different names and ID:s on your inputs. However, if you can manage to have the same for both (i.e. component_0, other_0 etc.), you can remove the "names" array and the "names" forEach.
When you want to add an input to your addon-div, just add the ID (and name if you decide to keep it), without the "_0", to the array/s as in the example.
Change the name to "otherName_0" and ID to "otherID_0" in your html and this should work.
var i = 1;
document.getElementById('launch').onclick = function(event) {
event.preventDefault();
var addOnDiv = document.getElementById('addon');
var container = document.getElementById('add-components')
var clonedNode = addOnDiv.cloneNode(true);
var ids = ['componentID', 'otherID'];
var names = ['componentName', 'otherName'];
ids.forEach(function(id) {
var currentInput = clonedNode.querySelector(`#${id}_0`);
currentInput.id = `${id}_${i}`;
});
names.forEach(function(name) {
var currentInput = clonedNode.querySelector(`input[name=${name}_0]`);
currentInput.name = `${name}_${i}`;
});
container.appendChild(clonedNode);
i++;
}
I'm trying to make an input change value depending on another inputs value.
What I've come up with so far is this. But when running the onchange commmand I get an error that updateCity doesn't exist. Even thou it's there. Am I doing something wrong, is pretty new to coding with javascript.
<div class="form-inline">
<div class="form-group">
<label class="sr-only" for="zip">Indtast postnummer</label>
<input class="form-control" type="text" name="register_zip" id="zip" placeholder="Indtast postnummer" value="#city.zip" onchange="updateCity(this.value)" />
</div> <!-- class="form-group" -->
<div class="form-group">
<label class="sr-only" for="city">Indtast by</label>
<input class="form-control" type="text" name="register_city" id="city" placeholder="Indtast by" value="#city.name" />
</div> <!-- class="form-group" -->
</div>
<script>
function updateCity(city_zip) {
var city = findCity(city_zip);
if(city != null){
document.getElementById("register_city").value = city_name;
}
};
function findCity(zip){
var cities = [];
#{
foreach (var c in cities)
{
<text>
cities.push({zip: #c.zip, name: #c.name});
</text>
}
}
for(var i=0;i<cities.length;i++){
if(cities[i].zip == zip){
return cities[i]
}
}
};
</script>