How can ı make capitalization checker with array some and map function? - javascript

I use OOP system. I have one product list add project and ı want to capitalization check. I know two solution for problem but doesn't work.
For example, I entered a product called "bag" and again I want the same product not to be capitalized. Different letters such as "bag" and "Bag" or "BAG" should not be written in capital letters. how can ı fix this? Thanks advance for answer. (You just need to answer one of the two solutions.) Full code: https://codepen.io/BerkayAkgurgen/pen/bGBNojw
// Some Solution
function addProductToUI(e) {
const productName = nameInput.value.trim().toLowerCase();
const productModel = modelInput.value.trim();
const productPrice = priceInput.value.trim();
let products = getTodosFromStorage();
const urunlerim = new Urunler(productName, productModel, productPrice);
if (productModel == "" || productName == "" || productPrice == "") {
UI.showAlert("danger", "Hatalı Giriş")
} else if (todos.some(a => a.trim().toLowerCase() == newTodoValuee)) {
console.log("sdaas");
return false;
} else {
let control = false;
const products = Storage.getProductsFromStorage();
products.forEach(function (product) {
if (productName === product.productName) {
control = true;
}
});
if (control === false) {
UI.urunEkle(urunlerim);
Storage.addProductsToStorage(urunlerim);
UI.showAlert("success", "Başarılı Giriş");
nameInput.value = "";
modelInput.value = "";
priceInput.value = "";
} else {
UI.showAlert("danger", "Aynı Marka Girilemez");
}
}
e.preventDefault();
}
// Map Solution
function addProductToUI(e) {
const productName = nameInput.value.trim().toLowerCase();
const productModel = modelInput.value.trim();
const productPrice = priceInput.value.trim();
let products = getTodosFromStorage();
var words = todos.map(w => w.toLowerCase());
const urunlerim = new Urunler(productName, productModel, productPrice);
if (productModel == "" || productName == "" || productPrice == "") {
UI.showAlert("danger", "Hatalı Giriş")
} else if (words.includes(productName)) {
e.preventDefault();
console.log("Aynı Todo");
nameInput.value = "";
return false;
} else {
let control = false;
const products = Storage.getProductsFromStorage();
products.forEach(function (product) {
if (productName === product.productName) {
control = true;
}
});
if (control === false) {
UI.urunEkle(urunlerim);
Storage.addProductsToStorage(urunlerim);
UI.showAlert("success", "Başarılı Giriş");
nameInput.value = "";
modelInput.value = "";
priceInput.value = "";
} else {
UI.showAlert("danger", "Aynı Marka Girilemez");
}
}
e.preventDefault();
}

Ok, your code is huge, makes sense I guess, so I'll just give you a function you can use to only return common letters from a given text element(so that you can work with it)
The idea of how the function is used is that you store all values as lowercase FROM THE INPUT and do checks when INPUT IS ALREADY LOWERED
var x=document.getElementById('x')
function lowerCaseInput(elem){return elem.value.toLowerCase()}
var obj={}
document.getElementById('b')
.addEventListener('click',function(ev){
var input=lowerCaseInput(x)
if(obj[input]){alert(`Error: "${input}" already exists`)}
else{obj[input]=1; console.log(obj)}
})
<input id="x" />
<button id="b">add value</button>

Related

regex match() isn't working with input.value

I have a problem with regex.
In my code I have an input when a player can write his name and then click the 'start' button to start the adventure.
The first condition is working fine. The player gets an error when the name isn't between 4 and 20 characters long.
When it comes to the next condition. The player gets an error no matter what will he write inside the input. When I changed the match() to test() there is an error in console, that the test() is not a function.
Please help me, what did I do wrong?
let actualPlace = 'mainMenu';
let playerName = '';
const playerNameContainer = document.querySelector('.playerName');
const start = document.querySelector('.start');
const regExpression = /^[a-zA-ZżźćńółęąśŻŹĆĄŚĘŁÓŃ0-9]$/;
start.addEventListener('click', function(){
if (actualPlace == 'mainMenu') {
playerNameValue = playerNameContainer.value;
playerNameLength = playerNameValue.length;
if (playerNameLength >= 4 && playerNameLength <= 20) {
if (playerNameValue.match(regExpression)) {
actualPlace = 'adventure';
playerName = playerNameContainer.value;
playerNameContainer.value = '';
} else {
errorMsg.innerHTML = 'error';
}
} else {
errorMsg.innerHTML = 'error';
}
}
})
your regular expression is matching only one single character; you need to add the + quantifier to match more than one character.
I also added different errors so you know what part is failing
Here its a working example:
let actualPlace = 'mainMenu';
let playerName = '';
const playerNameContainer = document.querySelector('.playerName');
const start = document.querySelector('.start');
const regExpression = /^[a-zA-ZżźćńółęąśŻŹĆĄŚĘŁÓŃ0-9]+$/;
const errorMsg = document.querySelector('.error');
start.addEventListener('click', function(){
if (actualPlace == 'mainMenu') {
playerNameValue = playerNameContainer.value;
playerNameLength = playerNameValue.length;
if (playerNameLength >= 4 && playerNameLength <= 20) {
if (playerNameValue.match(regExpression)) {
actualPlace = 'adventure';
playerName = playerNameContainer.value;
playerNameContainer.value = '';
errorMsg.innerHTML = 'Success!';
} else {
errorMsg.innerHTML = 'error: your name must not contain spetial characters';
}
} else {
errorMsg.innerHTML = 'error: your name must be between 4 and 20 characters';
}
}
})
<input class="playerName" /><br />
<button class="start" >Start</button>
<div class="error" ></div>

JS Promise Ignored (not sure)

I am working on an alert-similar function in javascript, and I got in trouble.
The code of the first function (prepBkCrt) looks like this:
function prepBkCrt() {
event.preventDefault();
crtBkMnl = true;
crtBkCnl = false;
const url = crtBkTab.querySelector("#url");
const name = crtBkTab.querySelector("#name");
if (name.value.length >= 17) {
poper("Bookmark","I will pass this part",true).then((response) => {
if (response === false) {
crtBkCnl = true;
hideBkTab();
return;
}
});
}
addBookmark(url.value,name.value);
if (crtBkCnl === false) {
poper("Bookmark","Bookmark successfully created!",false);
}
url.value = "";
name.value = "";
}
and the second function looks like this:
function poper(headerTxt, descTxt, option) {
return new Promise((resolve, reject) => {
const poper = document.querySelector("#poper");
const header = poper.querySelector("h2");
const buttonDiv = poper.querySelector("div");
const desc = poper.querySelector("span");
header.innerText = headerTxt;
desc.innerHTML = descTxt;
const yBtn = buttonDiv.querySelectorAll("button")[0];
yBtn.addEventListener("click", (event) => {poper.style.transform = "translateY(-300px)"; resolve(true);});
const nBtn = buttonDiv.querySelectorAll("button")[1];
nBtn.addEventListener("click", (event) => {poper.style.transform = "translateY(-300px)"; resolve(false);});
if (option === false) {
nBtn.style.display = "none";
} else {
nBtn.style.display = "block";
}
poper.style.transform = "none";
setTimeout(() => {poper.style.transform = "translateY(-300px)"; resolve(false);},10000);
});
}
This used to work well on other code, but it seems to not work on this javascript file. I've checked that it does run the first poper function in prepBkCrt function, which is the problem. The expected behavior is if the name.value's length is over 17, it should run poper function (it should work like this, and run this one, but the code only runs the second image. What's the problem?
You seem to be looking for an else statement. The return inside the .then() callback does not break from prepBkCrt.
function prepBkCrt() {
event.preventDefault();
crtBkMnl = true;
crtBkCnl = false;
const url = crtBkTab.querySelector("#url");
const name = crtBkTab.querySelector("#name");
if (name.value.length >= 17) {
poper("Bookmark","I will pass this part",true).then(response => {
if (response === false) {
crtBkCnl = true;
hideBkTab();
}
});
} else {
addBookmark(url.value,name.value);
poper("Bookmark","Bookmark successfully created!",false);
url.value = "";
name.value = "";
}
}

How to prevent functions running if input value is empty or null? Vanilla JavaScript

I would like this list to only add list items and update the count if the user input, saved as variable 'x,' is not empty or null. However, the addNewItem() and updateCount() functions seem to be running regardless of what the input value is.
const title = document.getElementById('title');
const list = document.getElementById('list');
const input = document.getElementById('todoInput');
const add = document.getElementById('add')
function todoList() {
var x = document.querySelector('#todoInput').value;
function checkInput(){
if (x == null || x == "") {
var p = document.createElement("P")
var emptyError = document.createTextNode("Please enter something for the list");
document.querySelector('#message').appendChild(emptyError);
}
}
checkInput();
function removeMsg() {
const elems = document.querySelector('#message');
setTimeout(function() {
document.querySelector("#message").innerHTML = "";
}, 4000);
}
removeMsg();
if (x !== null || x !== "") {
function addNewItem() {
console.log('something');
const item = input.value;
const text = document.createTextNode(item);
const newItem = document.createElement('li');
const check = document.createElement('span');
check.className = 'circle';
newItem.appendChild(check);
newItem.appendChild(text);
list.appendChild(newItem);
input.value = '';
}
addNewItem();
function updateCount() {
const count = list.childElementCount;
title.innerHTML = `You have ${count} to-dos.`;
}
updateCount();
}
}
todoList();
You can check with if (x != null && x != "") to check against empty or null values. However you can also do like this:
if(x)
This will ensure if the value of x are not just non-empty and not-null, but also check against all the falsy values such as NaN, undefined etc and will only only the truthy values to pass in.

Multiple elements -> one function while the elements do not colide with each other

I have multiple selectiontags on different picture slides but same page. Each slide has a set of selectiontags and I want users to only choose 1 selectiontag. I have written the code to do this but I wonder if there is another way.
So, basically I want:
Slide1 w. selectiontags1: Choose 1 selectiontag (out of 4)
Slide2 w.selectiontags2: Choose 1 selectiontag
Slide3 w. selectiontags3: Choose 1 selectiontag
Slide4 w. selectiontags4: Choose 1 selectiontag
This is my code so far.
var prevSelectedValue = null;
var prevSelectedValue2 = null;
var prevSelectedValue3 = null;
var prevSelectedValue4 = null;
$w.onReady(function () {
//TODO: write your page related code here...
let tags = $w('#selectionTags1');
if (tags.value.length === 1) {
prevSelectedValue = tags.value[0];
} else if (tags.value.length > 1) {
tags.value = [];
}
let tags2 = $w('#selectionTags2');
if (tags2.value.length === 1) {
prevSelectedValue2 = tags2.value[0];
} else if (tags2.value.length > 1) {
tags2.value = [];
}
let tags3 = $w('#selectionTags3');
if (tags3.value.length === 1) {
prevSelectedValue3 = tags3.value[0];
} else if (tags3.value.length > 1) {
tags3.value = [];
}
let tags4 = $w('#selectionTags4');
if (tags4.value.length === 1) {
prevSelectedValue4 = tags4.value[0];
} else if (tags4.value.length > 1) {
tags4.value = [];
}
});
export function selectionTags1_change(event) {
//Add your code for this event here:
if (!event.target.value || event.target.value.length === 0) {
event.target.value = [prevSelectedValue];
} else {
event.target.value = event.target.value.filter(x => x !== prevSelectedValue);
prevSelectedValue = event.target.value[0];
}
}
export function selectionTags2_change(event) {
//Add your code for this event here:
if (!event.target.value || event.target.value.length === 0) {
event.target.value = [prevSelectedValue2];
} else {
event.target.value = event.target.value.filter(x => x !== prevSelectedValue2);
prevSelectedValue2 = event.target.value[0];
}
}
export function selectionTags3_change(event) {
//Add your code for this event here:
if (!event.target.value || event.target.value.length === 0) {
event.target.value = [prevSelectedValue3];
} else {
event.target.value = event.target.value.filter(x => x !== prevSelectedValue3);
prevSelectedValue3 = event.target.value[0];
}
}
export function selectionTags4_change(event) {
//Add your code for this event here:
if (!event.target.value || event.target.value.length === 0) {
event.target.value = [prevSelectedValue4];
} else {
event.target.value = event.target.value.filter(x => x !== prevSelectedValue4);
prevSelectedValue4 = event.target.value[0];
}
}
Just a couple notes to help clean up the code:
It is better to use event.target.value[event.target.value.length-1] instead of .filter(). While it doesn't make a huge performance difference since our array is so small, we know that the most recently selected item is the last in the array, so using length-1 is more efficient code.
It is better to manipulate the selector and not the event, so I would recommend replacing event.target.value = event.target.value.filter... with $w('#selectionTags2') = event.target.value[..... This will also make your code more readable as you know which element is being updated.
If you are not preloading anything into the $w('#selectionTags') value array, I am not sure the code in your onReady function is necessary (unless I am missing a step where you do populate that selection value array).

Why does this form keep on submitting even if it fails the validation?

I am new to javascript. I would like someone to explain to me why this form keeps getting submitted even if it fails the validation? I am not allowed to use any validation plugins hence I wrote several functions for validation.
/* EMAIL VALIDATION */
let validateEmailInput = (anEmail) => {
let emailRegex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (anEmail.value.search(emailRegex) !== -1 || anEmail.value.match(emailRegex)) {
document.getElementById("errorOutput1").innerText = "";
return true;
} else {
document.getElementById("errorOutput1").innerText = "Invalid email!";
anEmail.focus();
return false;
}
}
/* RADIO VALIDATION */
let validateRadioInput = (name) => {
let radios = document.getElementsByName("part1_radio");
let isCheckedRadio = false;
let numRadioChecked = 0;
let radioChosen;
for (let i = 0; i < radios.length && !isCheckedRadio; i++) {
if (radios[i].checked) {
numRadioChecked++;
document.getElementById("errorOutput2").innerText = "";
radioChosen = radios.item(i).id;
isCheckedRadio = true;
}
} //end for
if (numRadioChecked === 0) {
document.getElementById("errorOutput2").innerText = "Please select one season!";
isCheckedRadio = false;
}
return isCheckedRadio;
}
/* CHECKBOX VALIDATION */
let validateCheckboxInput = (name) => {
let checkboxGroup = document.getElementsByName("part1_checkbox");
let isCheckedCheckbox = false;
let numCheckboxChecked = 0;
let checkboxChosen;
for (let i = 0; i < checkboxGroup.length && !isCheckedCheckbox; i++) {
if (checkboxGroup[i].checked) {
numCheckboxChecked++;
document.getElementById("errorOutput3").innerText = "";
checkboxChosen = checkboxGroup[i];
isCheckedCheckbox = true;
} else {
// if (numCheckboxChecked === 0) {
document.getElementById("errorOutput3").innerText = "Please check at least one country!";
isCheckedCheckbox = false;
}
} // end for
return isCheckedCheckbox;
}
/* SELECT/OPTIONS VALIDATION */
let validateSelectInput = (aSelection) => {
let selectGroup = document.getElementsByName("part1_select");
let isCheckedSelect = false;
let numCheckedSelect = 0;
let selectedVar;
if (!selectGroup.value) {
document.getElementById("errorOutput4").innerText = "Please choose one!";
isCheckedSelect = false;
} else {
isCheckedSelect = true;
selectedVar = selectGroup.value;
}
return isCheckedSelect;
}
This function is called inline like this:
<form id="myForm_part1" name="myForm_part1"action="someemailhere" method="post" onsubmit="validateForm(this.form);" novalidate>
I need help understanding why this happens.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function() {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
return false;
}
});
}
There is an issue with the onsubmit handler. Try changing
onsubmit="validateForm(this.form);"
to
onsubmit = "return validateForm(this.form);"
Without the return statement the submit handler, which is a function compiled from the attribute value, returns undefined because it doesn't have a return statement.
Use preventDefault() to stop submission if validation fails.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function(event) {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
event.preventDefault();
}
});
}

Categories

Resources