Detect duplication of values of input fields - javascript

I have a big html form with multiple email fields. What I want to do is make sure the user can't enter the same email in more than one field.
I have managed to detect duplication successfully by defining an array where each email value the user inputs is pushed to the array and that's where the comparison happens.
the problem happens when after detecting duplication I delete the value from the input field but the value still exists in the array so my function still returns that there is a duplicate value.
here is my function code:
var filledEmail = [];
var allEmailFields = $("form input[type='email']");
function checkIfArrayIsUnique(myArray) {
return myArray.length === new Set(myArray).size;
}
function addToEmails() {
allEmailFields = $("form input[type='email']");
filledEmail = [];
allEmailFields.each(function(){
var currentEmail = $(this);
currentEmail.bind('change',function() {
console.log("email value changed");
filledEmail.push(currentEmail.val());
console.log(filledEmail);
if (checkIfArrayIsUnique(filledEmail) == true) {
console.log("emails unique")
}
else {
console.log("emails not unique");
}
})
});
}
Any help would be so much appreciated.

This is how you could do it:
Attach change event listeners to each of your elements and check if the entered value exists. If it does not exist add it to your filledEmail array otherwise do nothing.
You will see that if you type the same name in different input element boxes it will not be added, hence will not appear as the output in the console
var filledEmail = [];
document.querySelectorAll("input[type='email']").forEach((mailField,i) => {
mailField.addEventListener("change", e => {
const email = e.target.value;
const hasMail = filledEmail.find(x => x === email);
if (!hasMail) {
filledEmail = filledEmail.filter((x, j)=> j!==i);
filledEmail.push(email);
}
console.log('filled mails without duplicates', filledEmail)
});
});
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />

Related

How to validate all inputs which exists on page?

All inputs from page
I have this html page which is dynamical created, which contains some divs. Every div-question(0,1,2, etc) contain an input based on which answer type the user chose. I want to validate every single inputs from page and:
If value of one input type number,text,date is != "" alert("something")
else send the value in an array;
If checkbox/radio is not checked alert("something");
I tried something like this:
let nrDiv = document.getElementsByClassName("div-question");
let existInput = nrDiv[0].querySelector("input[type='text']");
let numberInput = nrDiv[0].querySelector("input[type='number']");
if (document.body.contains(existInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container[0].querySelector("input[type='text']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
It's working but if I come with another for loop, for input type="number" is not working anymore. I'm getting value null. So if I come with this:
if (document.body.contains(numberInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container.querySelector("input[type='number']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
And for the checkbox and radio inputs I don't have any idea. I want something like this:
If all inputs are not empty and minimum one checkbox/radio is checked, send the answer and question in an array else alert("error");
I feel like this is simple once you add the required attribute and/or a pattern.
This is a simple POC:
<form action="">
<input type="text" required>
<input type="number" required>
<input type="checkbox" required>
<input type="radio" required>
<input type="date" required>
<button type="submit">Submit</button>
</form>
Notice that when you click the submit button, it does the verification you want, in this case != "".

Check if value matches any of the other values in array in JS ES6

I have tried a few things. Not sure where I'm going wrong.
I have a form where the user needs to put in all the people who are attending:
Person 1
Name
DOB
Email
Person 2
Name
DOB
Email
etc
I need to work out if any of the "Email" values are the same.
So I orginally thought get all the inputs:
let checkEmails = document.querySelectorAll("[data-email='email']");
and when each of those is updated run a function to check and pass the value:
for (const inputs of Array.from(checkEmails)) {
inputs.onchange = function(){
const value = this.value;
checkMatchingEmails(value);
};
}
First I tried using the "includes" method, but it was always returning "doesn't match", wasn't sure how to debug that so I tried different methods.
function checkMatchingEmails(value){
if (Array.from(checkEmails).includes(({ value }) == value)) {
console.log("matches");
} else {
console.log("doesnt match");
}
}
checkMatchingEmails();
If you can see my issue here please stop reading as I just mention other methods I tried:
Another method:
function checkMatchingEmails(value){
let checkEmailValues = document.querySelectorAll("[data-pnr-field='passportNumber'].value");
for (const inputValues of Array.from(checkEmailValues)) {
if(inputValues == value) {
console.log("matches");
} else {
console.log("doesnt match");
}
}
}
checkMatchingEmails();
Hope you can help me.
Solved it with:
let checkEmails = [];
const checkEmailValues = document.querySelectorAll("[data-pnr-field='passportNumber']");
checkEmailValues.forEach(item => item.addEventListener('change', checkMatchingEmailValues));
function checkMatchingEmailValues(e) {
const email = e.target.value;
if(checkEmails.includes(email)){
console.log("email matches");
console.log(e);
} else {
console.log("email doesnt match");
checkEmails.push(email);
}
console.log(checkEmails);
}
There are a couple of mistakes in your code.
Mistake 1
document.querySelectorAll("[data-email='email']")
returns a NodeList.
You cannot check if it includes a string value and will always return false.
You should check the documentation on Array.includes
Mistake 2
inputs.onchange = function(){
This is not how we add event listeners.
Use inputs.addEventListener("change", function)
Refer the documentation here 👉 Event handlers
Possible solution
You should basically create an Array of string values and do an includes on the same. Also you might need to track the index of each element.
A rough implementation might look like below. You can run the snippet and see the validation errors.
let checkEmails = document.querySelectorAll("[data-email='email']");
let emailsEntered = [];
for (let i = 0; i < checkEmails.length; i++) {
checkEmails[i].addEventListener("change", (e) => {
const value = e.target.value;
if (!checkMatchingEmails(value)) {
emailsEntered[i] = value;
e.target.nextElementSibling.innerHTML = "";
} else {
e.target.nextElementSibling.innerHTML =
`This value is already entered at index ${emailsEntered.indexOf(value)}`
}
console.log(emailsEntered);
});
}
function checkMatchingEmails(value) {
return emailsEntered.includes(value);
}
<input type="text" placeholder="Enter a value" data-email="email" />
<div id="error" style="color:red"></div>
<input type="text" placeholder="Enter a value" data-email="email" />
<div id="error" style="color:red"></div>
<input type="text" placeholder="Enter a value" data-email="email" />
<div id="error" style="color:red"></div>
<input type="text" placeholder="Enter a value" data-email="email" />
<div id="error" style="color:red"></div>
Please note that this is just a rough draft and not all the edge cases might be handled.

how to remember inputs value by using local storage?

I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.
here is the HTML code
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
and here is javascript
<script type="text/javascript">
var nameArr = ["name"];
var inputs = document.getElementsByName('name');
inputs.forEach(function(el){
el.value = getSavedValue(el);
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
</script>
if there is a way to solve this problem please tell me.
and if there is a way to do that with jquery I will be thankful to tell me that.
Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.
Secondly use a common class inputs in this case and give separate name to each element.
Then get all the elements with same class, iterate through it and get value of name property using getAttribute. Use this value to check if there exist a key in localStorage
var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
console.log()
el.value = getSavedValue(el.getAttribute('name'));
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
<input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" />
On your code you are passing the input object as a parameter instead of its name (or value; you choose). As localStorage only stores String key-value pairs, it won't work as you're trying to find a key that is an object.
in the forEach instead of:
el.value = getSavedValue(el);
set:
el.value = getSavedValue(el.name);
or let the "getSavedValue" function accept an object as parameter, but to access localStorage you must pass a string as the key.

How to save data from a form with HTML5 Local Storage?

I have a form that makes logging into a website but not in mine and I want them to be saved form data in my web with HTML5 local storage. But not how. Any idea? My form is this:
<form action="http://issuefy.ca.vu/on/login.php" class="form-login" method="post" />
<input name="email" type="email" id="email" required="" placeholder="Email" />
<input name="password" type="password" required="" placeholder="Contraseña" />
</form>
LocalStorage has a setItem method. You can use it like this:
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
When you want to get the value, you can do the following:
var storedValue = localStorage.getItem("email");
It is also possible to store the values on button click, like so:
<button onclick="store()" type="button">StoreEmail</button>
<script type="text/javascript">
function store(){
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
}
</script>
Here's a quick function that will store the value of an <input>, <textarea> etc in local storage, and restore it on page load.
function persistInput(input)
{
var key = "input-" + input.id;
var storedValue = localStorage.getItem(key);
if (storedValue)
input.value = storedValue;
input.addEventListener('input', function ()
{
localStorage.setItem(key, input.value);
});
}
Your input element must have an id specified that is unique amongst all usages of this function. It is this id that identifies the value in local storage.
var inputElement = document.getElementById("name");
persistInput(inputElement);
Note that this method adds an event handler that is never removed. In most cases that won't be a problem, but you should consider whether it would be in your scenario.
Here,Simple solution using JQUERY is like this..
var username = $('#username').val();
var password = $('#password').val();
localStorage.setItem("username", username);
localStorage.setItem("password", password);
To save the data you have to use
localStorage.setItem method and to get the data you have to use
localStorage.getItem method.
This is my function from my CMS, that save all TEXTAREA and INPUT values on "keyup"
and place it in the right element on reload.
After the form has been submitted, only the submitted form is deleted from the local storage.
Set it to buttom of your page, thats it.
(function (mz,cms,parentKey,subKey) {
setTimeout(function() {
const storeAll = "textarea,input";
const formArray = mz.querySelectorAll(storeAll);
parentKey = window.location.href+"-";
formArray.forEach((formItem) => {
if (formItem) {
subKey = formItem.getAttribute("name");
var key = parentKey+subKey;
if (localStorage[key]) {
var _localStorage = localStorage[key] ;
formItem.value = _localStorage;
}
formItem.addEventListener("keyup", function () {
var _localStorage = formItem.value;
var T = formItem.getAttribute("type");
if (T == "password" || T == "hidden" || T == "submit" || formItem.disabled) {
//console.log("Ignore: "+formItem.getAttribute("name"));
return;
}
localStorage.setItem(key, _localStorage);
} , false);
formItem;
}
});
const submitForm = mz.querySelectorAll("form");
submitForm.forEach((submitItem) => {
if (submitItem) {
submitItem.addEventListener("submit", function (e) {
// e.preventDefault();
const formArray = submitItem.querySelectorAll("textarea,input");
formArray.forEach((formItem) => {
subKey = formItem.getAttribute("name");
localStorage.removeItem(parentKey+subKey);
} , false);
} , false);
}
});
}, 1);
}(this.document,'','',''));

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources