Why doesn't e.preventDefault() stop my page from Refreshing? - javascript

I just can't figure out, why my site is loading when pushing the submit-btn. Even though I tried to prevent this with e.preventDefault() in my function. Maybe someone can open my eyes.. I'm sitting next to this (small) problem since 2 Days.
class Einkauf {
constructor(produkt, anzahl){
this.produkt = produkt;
this.anzahl = anzahl;
}
};
class UI {
static showItems () {
const items = [{
Produkt: "Butter",
Anzahl: 2
},{
Produkt: "Käse",
Anzahl: 1
}];
items.forEach(item => UI.addItems(item));
}
static addItems (item) {
const container = document.getElementById('grocery-list');
const newItem = document.createElement('tr');
newItem.innerHTML =
`<td>${item.Produkt}</td>
<td>${item.Anzahl}</td>
<td><a class="btn btn-danger btn-sm delete">x</a></td>`
container.appendChild(newItem);
}
};
document.addEventListener('DOMContentLoaded', UI.showItems());
//Neues Produkt einpflegen:
document.getElementById('btn').addEventListener('submit', (e) => {
e.preventDefault();
//Inputs definieren:
const produkt = document.getElementById('produkt').value;
const anzahl = document.getElementById('anzahl').value;
const einkauf = new Einkauf(produkt, anzahl);
UI.addItems(einkauf);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Einkaufsliste</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch#4.5.2/dist/yeti/bootstrap.min.css" integrity="sha384-mLBxp+1RMvmQmXOjBzRjqqr0dP9VHU2tb3FK6VB0fJN/AOu7/y+CAeYeWJZ4b3ii" crossorigin="anonymous">
</head>
<body>
<div class="container mx-auto">
<h1 class="text-center my-5 display-6">
<span class="text-primary m-0">Einkaufs</span>
liste
</h1>
<form id="form">
<div class="form-group">
<label for="produkt">Was fehlt?</label>
<input type="text" id="produkt" class="form-control">
</div>
<div class="form-group">
<label for="anzahl">Wie viel fehlt?</label>
<input type="number" id="anzahl" class="form-control">
</div>
<input id="btn" type="submit" value="Hinzufügen" class="btn btn-primary btn-block">
</form>
<table class="table table-striped mt-5">
<thead class="text-primary font-weight-bold">
<td>Marke:</td>
<td>Menge:</td>
<td></td>
</thead>
<tbody id="grocery-list">
</tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Maybe someone can figure the problem out and give me a short advice.
Best regards, Philipp.

You should instead be listening to the submit event on the form:
document.getElementById('form').addEventListener('submit', function(e) {
e.preventDefault()
const produkt = document.getElementById('produkt').value;
const anzahl = document.getElementById('anzahl').value;
const einkauf = new Einkauf(produkt, anzahl);
UI.addItems(einkauf);
})
class Einkauf {
constructor(produkt, anzahl) {
this.produkt = produkt;
this.anzahl = anzahl;
}
};
class UI {
static showItems() {
const items = [{
Produkt: "Butter",
Anzahl: 2
}, {
Produkt: "Käse",
Anzahl: 1
}];
items.forEach(item => UI.addItems(item));
}
static addItems(item) {
const container = document.getElementById('grocery-list');
const newItem = document.createElement('tr');
newItem.innerHTML =
`<td>${item.Produkt}</td>
<td>${item.Anzahl}</td>
<td><a class="btn btn-danger btn-sm delete">x</a></td>`
container.appendChild(newItem);
}
};
document.addEventListener('DOMContentLoaded', UI.showItems());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Einkaufsliste</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch#4.5.2/dist/yeti/bootstrap.min.css" integrity="sha384-mLBxp+1RMvmQmXOjBzRjqqr0dP9VHU2tb3FK6VB0fJN/AOu7/y+CAeYeWJZ4b3ii" crossorigin="anonymous">
</head>
<body>
<div class="container mx-auto">
<h1 class="text-center my-5 display-6">
<span class="text-primary m-0">Einkaufs</span> liste
</h1>
<form id="form">
<div class="form-group">
<label for="produkt">Was fehlt?</label>
<input type="text" id="produkt" class="form-control">
</div>
<div class="form-group">
<label for="anzahl">Wie viel fehlt?</label>
<input type="number" id="anzahl" class="form-control">
</div>
<input id="btn" type="submit" value="Hinzufügen" class="btn btn-primary btn-block">
</form>
<table class="table table-striped mt-5">
<thead class="text-primary font-weight-bold">
<td>Marke:</td>
<td>Menge:</td>
<td></td>
</thead>
<tbody id="grocery-list">
</tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Maybe someone can figure the problem out and give me a short advice. Best regards, Philipp.

Related

how can I resolve sweetalert background distortion?

enter image description here
Upper image is the Sign-in page.
I added sweetalert, and it goes wrong like below.
(the alert set in the middel, and my sign-in form goes up! It should be located in the middle!)
(I added the alert appear when the ID or password value is null or empty.)
login equals sign-in
what's wrong with my code?
Here is my full code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.101.0">
<title>Floating labels example · Bootstrap v4.6</title>
<!-- Bootstrap core CSS -->
<!-- <link href="/css/bootstrap.min.css" rel="stylesheet">-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/product/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="/css/floating-labels.css" rel="stylesheet">
</head>
<body>
<div class="form-signin" style="max-width: 520px">
<div class="text-center mb-4">
<!-- TODO 로그인페이지 로고 추가할 자리 -->
<!-- <img class="mb-4" src="/brand/bootstrap-solid.svg" alt="" width="72" height="72">-->
<h1 class="h3 mb-3 font-weight-normal">로그인 </h1>
</div>
<div class="form-label-group">
<input id="user_id" class="form-control" placeholder="id" required autofocus>
<label for="inputId">ID를 입력하세요</label>
</div>
<div class="form-label-group">
<input type="password" id="password" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password를 입력하세요</label>
</div>
<div>
<button class="btn btn-outline-primary form-control" id="loginBtn" onclick="login()">로그인</button>
</div>
<hr class="mb-4">
<div class="btn-group row" style="width:100%; --bs-gutter-x: 0">
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;">아이디
찾기
</button>
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;">비밀번호
찾기
</button>
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;"
onclick="joinBtn()">회원가입
</button>
</div>
<p class="mt-5 mb-3 text-muted text-center">© 2017-2022</p>
</div>
</body>
</html>
<script>
var input = document.getElementById("password");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("loginBtn").click();
}
});
var passwordForm = document.querySelector("#password");
function login() {
let userIdValue = document.querySelector("#user_id").value;
let passwordValue = document.querySelector("#password").value;
if (userIdValue == null || userIdValue == "") {
document.querySelector("#user_id").focus();
Swal.fire(
'ID가 비었습니다!',
'로그인 할 계정의 ID를 입력해주세요!',
'question'
)
return;
}
if (passwordValue == null || passwordValue == "") {
document.querySelector("#password").focus();
Swal.fire(
'비밀번호가 비었습니다!',
'로그인 할 계정의 비밀번호를 입력해주세요!',
'question'
)
return;
}
let info = {
userId: userIdValue,
password: passwordValue
}
$.ajax({
url: "/login/check/api",
method: "POST",
contentType: "application/Json",
data: JSON.stringify(info),
success: function (a) {
location.href = "/"
},
error: function (a, b) {
let errorA = a
Swal.fire({
icon: 'error',
title: '로그인 실패',
text: errorA.responseText,
})
//alert(a.responseText);
}
})
}
function joinBtn() {
location.href = "/join/form"
}
</script>
let me know how can I solve this problem
Before the alert comes out, I think the HTML should be on the screen first to solve the problem, but I don't know what to do.

Making a href variable that changes with text input

I'm trying to make a mailto: link change based on a text input and a button.
I managed to make it work without a href, with just plain text from a paragraph, but i can't manage to make it work on the href.
I get either [object HTMLInputElement] or undefined
HTML
<input type="text" id="email_input"><br>
<span id="links"><a id="email">email</a></span><br>
<input type="button" id="btn" value="Submit"><br>
JAVASCRIPT
var emailIN = document.getElementById('email_input');
var emailOUT = document.getElementById('email');
var emailLink = "mailto:"+emailOUT;
btn.onclick = function(){
/* addressOUT.textContent = addressIN.value; */
/* emailOUT.setAttribute("href",emailIN); */
/* emailOUT.textContent = "mailto:"+emailIN.value; */
/* $("a#email").attr('href','mailto:'+emailIN); */
/* document.querySelector("#email").href=emailLink; */
document.getElementById("email").value = "mailto:"+emailIN
emailOUT.href = "mailto:"+emailIN;
}
Here is an example.
document.getElementById('btn').addEventListener('click', function() {
const emailInput = document.getElementById('email_input');
const emailLink = document.getElementById('email');
const href = emailInput.value != '' ? 'mailto:' + emailInput.value : '';
if (href.length > 0) {
emailLink.setAttribute('href', href);
console.log(`Link href is change to ${href}`);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="my-5">
<div class="mb-3">
<label for="email_input" class="form-label">Email address</label>
<input class="form-control" id="email_input" placeholder="name#example.com" />
</div>
<div class="mb-3">
<a id="email" href="">Email Link</a>
</div>
<div class="mb-3">
<button type="button" id="btn" class="btn btn-primary btn-md">Submit</button>
</div>
</div>
</div>
</body>
</html>

How can I redirect to another page after verifying the credit card validation?

I need help about redirect another page after credit card valitaditon success.php
Well i dont know anything about vue.
i found something like (onSubmit () {
axios.get('success.php', { )
Something like this? Any help to this poor guy. Thanks :)
Here is vue codes.
<script src="../dist/vue-credit-card-validation.js"></script>
<script type="text/javascript">
const { createApp, ref } = Vue;
const Example = {
computed: {
cardBrandClass(){
return this.getBrandClass(this.cardBrand);
}
},
data() {
return {
cardNumber: null,
cardExpiry: null,
cardCvc: null,
cardPostal: null,
cardErrors: {},
// declaring card-brand in data{} enables card brand name/classes.
cardBrand: null,
}
},
methods: {
validate: function(){
// init
this.cardErrors = {};
// validate card number
if(!this.$cardFormat.validateCardNumber(this.cardNumber)){
this.cardErrors.cardNumber = "Invalid Credit Card Number.";
};
// validate card expiry
if (!this.$cardFormat.validateCardExpiry(this.cardExpiry)) {
this.cardErrors.cardExpiry = "Invalid Expiration Date.";
};
// validate card CVC
if (!this.$cardFormat.validateCardCVC(this.cardCvc)) {
this.cardErrors.cardCvc = "Invalid CVC.";
};
},
reset: function(){
this.cardErrors = {};
this.cardNumber = null;
this.cardExpiry = null;
this.cardCvc = null;
this.cardPostal = null;
this.$refs.cardNumInput.focus();
},
prefill: function(ccNum){
this.cardNumber = ccNum;
this.$cardFormat.setCardType({
currentTarget : this.$refs.cardNumInput,
value: ccNum
});
},
getBrandClass: function (brand) {
let icon = '';
brand = brand || 'unknown';
let cardBrandToClass = {
'visa': 'fab fa-cc-visa',
'mastercard': 'fab fa-cc-mastercard',
'amex': 'fab fa-cc-amex',
'discover': 'fab fa-cc-discover',
'diners': 'fab fa-cc-diners-club',
'jcb': 'fab fa-cc-jcb',
'unknown': 'fa fa-credit-card',
};
if (cardBrandToClass[brand]) {
icon = cardBrandToClass[brand];
};
return icon;
}
},
watch: {
// handle auto-focus to next field
// Note: since CVC can be 3 OR 4 digits we don't watch it
cardNumber: function(val){
if(this.$cardFormat.validateCardNumber(val)){
this.$refs.cardExpInput.focus();
}
},
cardExpiry: function (val) {
if (this.$cardFormat.validateCardExpiry(val)) {
this.$refs.cardCvcInput.focus();
}
}
},
onMounted(){
this.$refs.cardNumInput.focus();
}
};
const app = createApp(Example);
app.use(VueCreditCardValidation);
app.mount('#app');
</script>
Here is html
<!DOCTYPE html>
<html>
<head>
<title>Card validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!-- Libraries only required for demo. -->
<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://unpkg.com/vue#next"></script>
</head>
<body>
<form >
<div class="row pt-4">
<div class="col-sm-12 col-md-6 col-lg-4">
<div class="form-group">
<label>Card Number:</label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i :class="cardBrandClass"></i></span>
</div>
<input ref="cardNumInput" :data-error="(cardErrors.cardNumber)?true:false" v-model="cardNumber" type="tel" class="form-control" placeholder="#### #### #### ####" v-cardformat:formatCardNumber>
</div>
<div v-if="cardErrors.cardNumber" class="error">
<small>{{ cardErrors.cardNumber }}</small>
</div>
</div>
</div>
</div>
<div class="row pt-2">
<div class="col-4 col-lg-2">
<div class="form-group">
<label>Card Expiration:</label>
<input ref="cardExpInput" id="card-exp" :data-error="(cardErrors.cardExpiry)?true:false" v-model="cardExpiry" maxlength="10" class="form-control" v-cardformat:formatCardExpiry>
<div v-if="cardErrors.cardExpiry" class="error">
<small>{{ cardErrors.cardExpiry }}</small>
</div>
</div>
</div>
<div class="col-4 col-lg-2">
<div class="form-group">
<label>Card CVC:</label>
<input ref="cardCvcInput" :data-error="(cardErrors.cardCvc)?true:false" v-model="cardCvc" class="form-control" v-cardformat:formatCardCVC>
<div v-if="cardErrors.cardCvc" class="error">
<small>{{ cardErrors.cardCvc }}</small>
</div>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label>Restrict Numeric:</label>
<input placeholder="Only numbers can be entered here..." v-model="cardPostal" class="form-control" v-cardformat:restrictNumeric>
</div>
</div>
</div>
<div class="row">
<div class="col-12 pt-2">
<button type="button" class="btn btn-primary" #click="validate">Validate Card Details</button>
<button type="button" class="btn btn-light" #click="reset">Reset</button>
</div>
</div>
</form>
</body>
</html>
I need help after validation confirm send to success.php page. Thanks.
If you are working with php/html files instead of an single page app, you could simply redirect the user with some basic javascript.
In your method, when you need to redirect the user after validating the card succesfully, just type:
window.location.replace("http://my-url.com/my.page");

What are the methods to limit the number and time of alerts?

when I click on the "Todo Ekleyin" button, I get a warning. However, I would like this alert to appear only once per press, not multiple times, and can be pressed again after the alert disappears. How can I achieve this and?
Thank you in advance for your answer, good work. (If there is a method other than the method you suggested, I would be glad if you can write its name.)
// Tüm Elementleri Seçme
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
eventListeners();
function eventListeners() { // Tüm Event Listenerlar
form.addEventListener("submit", addTodo);
}
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") { // Alarm Verme
showAlert("danger","Lütfen Bir Todo Giriniz");
}
else {
addTodoToUI(newTodo);
}
addTodoToUI(newTodo);
e.preventDefault();
}
function showAlert(type,message){
const alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.textContent = message;
firstCardBody.appendChild(alert);
//setTimeout
setTimeout(function(){
alert.remove();
}, 1000);
}
function addTodoToUI(newTodo) { // String Değerini List Item olarak Ekleyecek.
// List Item Oluşturma.
const listItem = document.createElement("li");
// Link Oluşturma
const link = document.createElement("a");
link.href = "#";
link.className = "delete-item";
link.innerHTML = "<i class = 'fa fa-remove'></i>";
listItem.className = "list-group-item d-flex justify-content-between";
// Text Node
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
// Todo List'e List Item'ı Ekleme
todoList.appendChild(listItem);
// Ekleme Sonrası Input'tan yazı Silme
todoInput.value = "";
}
// Todo Ekleme Bilgi Mesajı
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<title>Todo List</title>
</head>
<body>
<div class="container" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body">
<form id="todo-form" name="form">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="todo" id="todo"
placeholder="Bir Todo Girin" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<hr />
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body">
<hr />
<h5 class="card-title" id="tasks-title">Todolar</h5>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="filter" id="filter"
placeholder="Bir Todo Arayın" />
</div>
</div>
<hr />
<ul class="list-group">
<!-- <li class="list-group-item d-flex justify-content-between">
Todo 1
<a href = "#" class ="delete-item">
<i class = "fa fa-remove"></i>
</a>
</li>-->
</ul>
<hr />
<a id="clear-todos" class="btn btn-dark" href="#">Tüm Taskları Temizleyin</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script src="berkay.js"></script>
</body>
</html>
You can put an integer in your alert function and every using array increase a one more.
For example, if you want after 5 times don't show alert.
var a = 0;
var b = true;
if (newTodo === "" || b) { // Alarm Verme
showAlert("danger","Please Give me a Todo!");
a++;
if(a == 5 ){
b = false;
}
}

Remove dynamically created elements in a form

I know this is a basic questions, but I am working on making a dynamic form and was having a bit of trouble figuring out how to delete elements that share the same class. I have looked around on the web and other posts for a means to accomplish this, but still was unable to figure it out.
I am new to this so I apologize for the basic question. Below, I have pasted the relevant code and my attempt at this. Would anyone be able to assist me?
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName){
if (ingCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement('directionSet');'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName){
if (dirCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
<!-- Required program scripts -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Style Sheets-->
<link rel="stylesheet" href="/styles/navBarStyle.css">
<link rel="stylesheet" href="/styles/myRecipesStyle.css">
<link rel="stylesheet" href="/styles/createRecipeStyle.css">
<link rel="stylesheet" href="/styles/errorMessageStyle.css">
</head>
<body>
<!-- Background image -->
<img id="background" src="/images/foodBackground.jpg" alt="">
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<%- include('../_partial/_messages'); -%>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/>
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
<!-- Required scripts to run app -->
<script src="/controls/newRecipeControl.js"></script>
<script src="/controls/errorMessageControl.js"></script>
</html>
Thanks for any help.
In your code you are using getElementById but there is no id called directionSet its a class.
You can simply use parentElement and remove to remove the newly added dynamic inputs by calling an onClick function.
In the onClick function removeElement() - this refers to the elements we have clicked and it will remove from the form.
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName) {
if (ingCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement(this);'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName) {
if (dirCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' onClick='removeElement(this);' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
elementId.parentElement.remove()
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
</head>
<body>
<!-- Background image -->
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" />
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
</html>

Categories

Resources