Javascript: modal.style.display = "block" not working - javascript

I made a modal that is supposed to pop up when the user clicks the edit button. I hid the modal in CSS with display: none;
for some reason for the JS side I made a function that is linked to the edit button that when button is pressed the modal is changed to display: block;
What I did do was within the function renderList() I used the button onclick="editItem(event, ${i})" for the function editItem(event, i)
/*----Edit budget Entry----*/
function editItem(event, i){
alert("edit button clicked")
let mod = modal.style.display = "block";
console.log(mod)
}
I made a runable code so you can see.
/*----Storage key----*/
const BUDGETLIST_KEY = "user-key-entryList";
/*----Generate ID----*/
const createId = () => `${Math.floor(Math.random() * 10000)}${(new Date().getTime())}`;
/*----Get current Date----*/
function createdDate() {
let currentDate = new Date();
let day = String(currentDate.getDate()).padStart(2, '0');
let month = String(currentDate.getMonth() + 1).padStart(2, '0');
let year = currentDate.getFullYear();
currentDate = month + '/' + day + '/' + year;
return currentDate;
}
/*----Variable Objects----*/
const el = {
list: document.querySelector(".list"),
cashflow: document.querySelector("#cashflow"),
catagory: document.querySelector(".catagory"),
label: document.querySelector(".label"),
number: document.querySelector(".number"),
modal: document.querySelector(".modal"),
};
/*----Array with local Storage----*/
let budgetArray = [];
/*----Budget list Object----*/
function makeNewBudget() {
const data = {
id: createId(),
cashflowNew: el.cashflow.value,
catagoryNew: el.catagory.value,
labelNew: el.label.value,
dateNew: createdDate(),
numberNew: el.number.value,
};
return data;
}
/*----Render Budget List----*/
function renderList() {
el.list.innerHTML = budgetArray.map(function(data, i) {
return `<div class="entry">
<div class="list">
<button onclick="deleteItem(event, ${i})" class="Archive" data-id="${data.id}">
<img src="../resources/Images/archive.png" alt="Archive">
</button>
<button onclick="editItem(event, ${i})" class = "edit" data-id="${data.id}" class = "edit" data-id="${data.id}">
<img src="../resources/Images/edit.png" alt="Edit">
</button>
<div class="input" data-id="${data.id}"></div>
<label class="dateNew">${data.dateNew}</label>
<label class="cashflowNew">${data.cashflowNew}</label>
<label class="catagoryNew">${data.catagoryNew}</label>
<label class="labelNew">${data.labelNew}</label>
<label class="numberNew">${data.numberNew}</label>
</div>
</div>`;
});
}
/*----form validation----*/
let budgetButton = document.querySelector(".budget-button");
let label = document.querySelector(".label");
let num = document.querySelector(".number");
budgetButton.addEventListener("click", () => {
if (!label.value || !num.value) {
alert("please make sure all inputs are filled");
}
budgetArray.push(makeNewBudget())
renderList();
});
/*----Remove from array----*/
function deleteItem(event, i) {
budgetArray.splice(i, 1);
renderList();
}
/*----Close Modal----*/
let close = document.querySelector(".btn-close")
let xBtn = document.querySelector(".btn-secondary")
let modal = document.querySelector(".modal-content")
close.addEventListener('click', () => {
if (close) {
modal.style.display = "none"
}
});
xBtn.addEventListener('click', () => {
if (xBtn) {
modal.style.display = "none"
}
});
/*----Edit budget Entry----*/
function editItem(event, i) {
alert("edit button clicked")
let mod = modal.style.display = "block";
console.log(mod)
}
.modal {
display: block;
margin-top: 15rem;
display: none;
}
<!--Create budget-->
<div class="create-budget">
<form class="budget">
<input class="budget-button" type="button" value="Create your budget">
<select id="cashflow" name="income/expense" class="income/expense">
<option class="options" value="income">Income</option>
<option class="options" value="expense">Expense</option>
</select>
<select name="Catagory" class="catagory" value="Catagory">
<option class="options" value="House Hold">House Hold</option>
<option class="options" value="Car">Car</option>
<option class="options" value="entertainment">Entertainment</option>
<option class="options" value="investments">Investments</option>
<option class="options" value="business">Business</option>
<option class="options" value="savings">Savings</option>
</select>
<input class="label" type="text" placeholder="Example rent">
<input class="number" type="number" placeholder="0,0">
</form>
</div>
<div class="new-budet">
<div class="title">
<h5>Date</h5>
<h5>Income/Expenses</h5>
<h5>Catagory</h5>
<h5>Items</h5>
<h5>Amount</h5>
</div>
</div>
<div class="list"></div>
<div class="budget-update"></div>
<div class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Want to make changes?</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form class="budget-update">
<select id="cashflow-update" name="income/expense" class="income/expense">
<option class="options-update" value="income">Income</option>
<option class="options-update" value="expense">Expense</option>
</select>
<select class="catagory-update" name="Catagory" value="Catagory">
<option class="options-update" value="House Hold">House Hold</option>
<option class="options-update" value="Car">Car</option>
<option class="options-update" value="entertainment">Entertainment</option>
<option class="options-update" value="investments">Investments</option>
<option class="options-update" value="business">Business</option>
<option class="options-update" value="savings">Savings</option>
</select>
<input class="label-update" type="text" placeholder="Example rent">
<input class="number-update" type="number" placeholder="0,0">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">
<img src="/resources/Images/Save-icon.png" alt="Save Icon">
</button>
</div>
</div>
</div>
</div>

Thanks to ethry answer it helped solve the problem. I forgot to add a variable for it
let modal= document.querySelector(".modal")
/*----Edit budget Entry----*/
function editItem(event, i){
modal.style.display = "block";
}

In order to use a variable, it needs to be defined. It looks like you accidentally left it undefined.
let modal = document.querySelector(".modal");
/*----Edit budget Entry----*/
function editItem(event, i){
modal.style.display = "block";
}
Or you could replace .querySelector(". with .getElementsByClassName(" and add [0] at the end.
More information about variables:
https://developer.mozilla.org/en-US/docs/Glossary/Variable

Related

Select only targeted item and remove it - clear innerHtml

I am currently building and invoice creator app as to practice javascript.
My goal is that when the user presses the "remove" button, only the clicked item will be removed from the list.
const theForm = document.getElementById('the-form');
const taskInput = document.getElementById('task-input');
const renderItem = document.querySelector('.render');
const selectOption = document.getElementById('amount');
const totalSum = document.getElementById('total-sum');
let totalAmount = 0;
theForm.addEventListener('submit', function(e) {
e.preventDefault();
totalAmount += parseInt(selectOption.value);
renderItem.innerHTML += `
<div class="render-item">
<div class="left-side">
<h2>${taskInput.value}</h2>
<button class='remove'>Remove</button>
</div>
<h2><span>$</span>${selectOption.value}</h2>
</div>
`;
totalSum.textContent = `$${totalAmount}`;
taskInput.value = '';
selectOption.value = '10';
const removeItem = document.querySelectorAll('.render-item');
removeItem.forEach((item) => {
item.addEventListener('click', function() {
renderItem.innerHTML = '';
totalAmount = 0;
totalSum.textContent = '';
});
});
});
<div class="outer-container">
<header>
<h1>Invoice creator</h1>
<p>Thanks for choosing RazCorp, LLC!</p>
</header>
<main class="inner-container">
<section class="form-enter">
<form id="the-form">
<input type="text" id="task-input" name="task-input" placeholder="Enter task" required />
<div class="amount-container">
<label for="amount">$</label>
<select name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<button id="submit-btn" class="submit" type="submit">+</button>
</form>
</section>
<section class="display">
<div class="task-total">
<h3>TASK</h3>
<h3>TOTAL</h3>
</div>
<div class="render"></div>
</section>
<section class="final-amount">
<div class="final-left">
<h3>NOTES</h3>
<p>We accept cash, credit card, or PayPal</p>
</div>
<div class="final-right">
<h3>TOTAL AMOUNT</h3>
<h1 id="total-sum"></h1>
</div>
</section>
<button id="send-invoice" class="send-invoice">
<span><i class="fa-solid fa-envelope"></i></span>Send invoice
</button>
</main>
</div>
First I am creating the Html through javascript and then I would like to remove it.
Right now when I press remove, every new created redenerItem is deleted and not just the one being clicked.
Any help appreciated :)
Because you have a single element that you're adding all of the entries to, when you press the remove button and it clears that single element, it clears all of the entries. What you probably want is a system that stores an array of all the items in the list, then selectively removing them. You might be able to use this:
const theForm = document.getElementById('the-form');
const taskInput = document.getElementById('task-input');
const selectOption = document.getElementById('amount');
const totalSum = document.getElementById('total-sum');
const renderItems = document.querySelector('.render');
const listItems = [];
let totalAmount = 0;
theForm.addEventListener('submit', function (e) {
e.preventDefault();
totalAmount += parseInt(selectOption.value);
//The Array.push method returns the new length of the array that we can use to get the item position
let itemPos = listItems.push(document.createElement('div')) - 1;
listItems[itemPos].innerHTML = `
<div class="left-side">
<h2>${taskInput.value}</h2>
<button class='remove' onclick='removeItem(${itemPos}, ${selectOption.value})'>Remove</button>
</div>
<h2><span>$</span>${selectOption.value}</h2>
`;
renderItems.appendChild(listItems[itemPos]);
totalSum.textContent = `$${totalAmount}`;
taskInput.value = '';
selectOption.value = '10';
});
//Move the remove item functionality to a new function
function removeItem(index, value) {
listItems[index].remove(); //Remove the element from the DOM
listItems.splice(index, 1); //Remove the element from the array
totalAmount -= value;
totalSum.textContent = `$${totalAmount}`;
}
<div class="outer-container">
<header>
<h1>Invoice creator</h1>
<p>Thanks for choosing RazCorp, LLC!</p>
</header>
<main class="inner-container">
<section class="form-enter">
<form id="the-form">
<input type="text" id="task-input" name="task-input" placeholder="Enter task" required />
<div class="amount-container">
<label for="amount">$</label>
<select name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<button id="submit-btn" class="submit" type="submit">+</button>
</form>
</section>
<section class="display">
<div class="task-total">
<h3>TASK</h3>
<h3>TOTAL</h3>
</div>
<div class="render"></div>
</section>
<section class="final-amount">
<div class="final-left">
<h3>NOTES</h3>
<p>We accept cash, credit card, or PayPal</p>
</div>
<div class="final-right">
<h3>TOTAL AMOUNT</h3>
<h1 id="total-sum"></h1>
</div>
</section>
<button id="send-invoice" class="send-invoice">
<span><i class="fa-solid fa-envelope"></i></span>Send invoice
</button>
</main>
</div>
const theForm = document.getElementById('the-form');
const taskInput = document.getElementById('task-input');
const renderItem = document.querySelector('.render');
const selectOption = document.getElementById('amount');
const totalSum = document.getElementById('total-sum');
let totalAmount = 0;
theForm.addEventListener('submit', function(e) {
e.preventDefault();
totalAmount += parseInt(selectOption.value);
renderItem.innerHTML += `
<div class="render-item">
<div class="left-side">
<h2>${taskInput.value}</h2>
<button class='remove'>Remove</button>
</div>
<h2><span>$</span>${selectOption.value}</h2>
</div>
`;
totalSum.textContent = `$${totalAmount}`;
taskInput.value = '';
selectOption.value = '10';
const removeItem = document.querySelectorAll('.render-item');
removeItem.forEach((item) => {
item.addEventListener('click', function() {
this.remove();
/*totalAmount = 0;
totalSum.textContent = '';*/
});
});
});
<div class="outer-container">
<header>
<h1>Invoice creator</h1>
<p>Thanks for choosing RazCorp, LLC!</p>
</header>
<main class="inner-container">
<section class="form-enter">
<form id="the-form">
<input type="text" id="task-input" name="task-input" placeholder="Enter task" required />
<div class="amount-container">
<label for="amount">$</label>
<select name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<button id="submit-btn" class="submit" type="submit">+</button>
</form>
</section>
<section class="display">
<div class="task-total">
<h3>TASK</h3>
<h3>TOTAL</h3>
</div>
<div class="render"></div>
</section>
<section class="final-amount">
<div class="final-left">
<h3>NOTES</h3>
<p>We accept cash, credit card, or PayPal</p>
</div>
<div class="final-right">
<h3>TOTAL AMOUNT</h3>
<h1 id="total-sum"></h1>
</div>
</section>
<button id="send-invoice" class="send-invoice">
<span><i class="fa-solid fa-envelope"></i></span>Send invoice
</button>
</main>
</div>
your event listener is already on the render-item, so just remove the element clicked.
now you will have the problem to update the amount and the text of 0.
you should add a class for the amount of each render-item, actually the amount is after the span that's it. If you have a class "render-item-amount" it would be easier at each update to modify the total

JS Function is not defined but it is

Hey guys I have this js snippet:
<script type="text/javascript">
function displayDeliveryOptions() {
var deliveryType = document.querySelector('input[name="deliveryType"]:checked').value;
if (deliveryType === "homedelivery") {
document.getElementById("pickupOptions").style.display = "none";
document.getElementById("deliveryOptions").style.display = "block";
} else {
document.getElementById("pickupOptions").style.display = "block";
document.getElementById("deliveryOptions").style.display = "none";
}
}
function updateDeliveryPrice() {
var selectedOption = document.querySelector('[name="deliveryTime"] option:checked');
document.querySelector('#deliveryPrice').value = selectedOption.dataset.price;
document.getElementById('priceLbl').innerHTML = selectedOption.dataset.price + '€';
var total = #Model.Total + parseInt(selectedOption.dataset.price);
totalLbl.textContent = total;
}
function submitForm() {
var formData = new FormData(document.getElementById("deliveryForm"));
fetch("/checkout", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
}
</script>
That applies to the following HTML:
<div><form id="deliveryForm" method="post">
<label>
<input type="radio" name="deliveryType" value="homedelivery" onchange="displayDeliveryOptions()"> Home Delivery
</label>
<br>
<label>
<input type="radio" name="deliveryType" value="pickup" onchange="displayDeliveryOptions()"> Pickup
</label>
<br>
<div id="pickupOptions" style="display:none">
<label for="pickupLocation">Pickup Location:</label><br>
<select name="pickupLocation">
#foreach (PickUp x in Model.PickUpList.DistinctBy(x => x.Location))
{
<option value="#x.Location">#x.Location</option>
}
</select>
<br>
<label for="pickupDate">Pickup Date:</label><br>
<select name="pickupDate">
#foreach (PickUp x in Model.PickUpList.DistinctBy(x => x.Timeslot.Date))
{
if (x.DeliveryStatus == DeliveryStatus.AVAILABLE)
{
<option value="#x.Timeslot.Date">#x.Timeslot.Date.ToShortDateString()</option>
}
}
</select>
<br>
<label for="pickupTime">Pickup Time:</label><br>
<select name="pickupTime">
#foreach (PickUp x in Model.PickUpList.DistinctBy(x => x.Timeslot.Time))
{
if (x.DeliveryStatus == DeliveryStatus.AVAILABLE)
{
<option value="#x.Timeslot.Time">#x.Timeslot.Time</option>
}
}
</select>
</div>
<div id="deliveryOptions" style="display:none">
<label for="deliveryDate">Delivery Date:</label><br>
<select name="deliveryDate">
#foreach (HomeDelivery x in Model.DeliveryList.DistinctBy(x => x.Timeslot.Date))
{
if (x.DeliveryStatus == DeliveryStatus.AVAILABLE)
{
<option value="#x.Timeslot.Date">#x.Timeslot.Date.ToShortDateString()</option>
}
}
</select>
<br>
<label for="deliveryTime">Delivery Time and Price:</label><br>
<select name="deliveryTime" onchange="updateDeliveryPrice()">
#foreach (HomeDelivery x in Model.DeliveryList.DistinctBy(x => x.Timeslot.Time))
{
if (x.DeliveryStatus == DeliveryStatus.AVAILABLE)
{
<option value="#x.Timeslot.Time" data-price="#x.Price">#x.Timeslot.Time - #x.Price</option>
}
}
</select>
<input type="hidden" name="deliveryPrice" id="deliveryPrice">
</div>
</form> <input class="btn btn-dark rounded-pill py-2 btn-block" type="button" value="Pay!" onclick="submitForm()" />
</div>
I get the error Uncaught ReferenceError: function is not defined on displayDeliveryOptions but it doesn't make any sense because it is defined.
Any ideas? I've been stuck on it for hours and I'm in an absolute deadlock.
Thank you in advance
EDIT: So apparently the JS snippets work, displayDeliveryOptions and submitForm work but only if updateDeliveryPrice is removed from the code, what is going on here?
EDI2: Fixed by changing the updateDeliveryPrice to
function updateDeliveryPrice() {
const deliveryTimeOption = document.querySelector('select[name="deliveryTime"] option:checked');
const deliveryPrice = deliveryTimeOption.getAttribute('data-price');
document.getElementById('deliveryPrice').value = deliveryPrice;
}
Fixed by changing the updateDeliveryPrice to
function updateDeliveryPrice() {
const deliveryTimeOption = document.querySelector('select[name="deliveryTime"] option:checked');
const deliveryPrice = deliveryTimeOption.getAttribute('data-price');
document.getElementById('deliveryPrice').value = deliveryPrice;
}
not sure where the error was but it works now! Yay!

How to swap options between two <select> list

I'm new to Javascript, and I want to swap these two options when the exchange button is clicked Page
HTML
<div class="form-group col-4">
<button type="button" class="btn bg-dark text-white" id="exchange" style="margin-top: 23px; margin-left: 10px;">
<i class="fa fa-exchange" aria-hidden="true"></i>
</button>
</div>
Javascript
function swap() {
let inp = document.getElementById("inputCurrency").value;
let out = document.getElementById("outputCurrency").value;
document.getElementById("inputCurrency").value = out;
document.getElementById("outputCurrency").value = inp;
}
let amountInput = document.getElementById("amount");
let inputCurrency = document.getElementById("inputCurrency");
let outputCurrency = document.getElementById("outputCurrency");
let convertButton = document.getElementById('convertButton');
convertButton.addEventListener("click",convertCurrency);
let exchangeButton = document.getElementById("exchange");
exchangeButton.addEventListener("click",swap());
You need remove function call in addEventListener, it contains only function name
exchangeButton.addEventListener("click",swap);
function swap() {
let inp = document.getElementById("inputCurrency").value;
let out = document.getElementById("outputCurrency").value;
document.getElementById("inputCurrency").value = out;
document.getElementById("outputCurrency").value = inp;
}
let amountInput = document.getElementById("amount");
let inputCurrency = document.getElementById("inputCurrency");
let outputCurrency = document.getElementById("outputCurrency");
let convertButton = document.getElementById('convertButton');
//convertButton.addEventListener("click",convertCurrency);
let exchangeButton = document.getElementById("exchange");
exchangeButton.addEventListener("click",swap);
<select id="inputCurrency">
<option value="1">USD</option>
<option value="2">KRW</option>
</select>
<select id="outputCurrency">
<option value="1">USD</option>
<option value="2">KRW</option>
</select>
<input type="text" id="amount"/>
<div class="form-group col-4">
<button type="button" class="btn bg-dark text-white" id="exchange" style="margin-top: 23px; margin-left: 10px;"> Exchange
<i class="fa fa-exchange" aria-hidden="true"></i>
</button>
</div>
<button id="convertButton">Convert</button>
addEventListener needs a function for second parameter. Add a callback function that calls swap() function.
exchangeButton.addEventListener("click", e => swap());

Display country state city names and display only country name in two fields

How to display country state city names. The result that I found is displaying only country name in rest two fields.
<html>
<head>
<title>dispaly country state district/title>
<link rel="stylesheet" href="coun.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script>
var stateObject = {
"India": { "AndhraPradensh": ["Guntur", "ananthapur","kurnool","krishna","kadapa"],
"Kerala": ["Thiruvananthapuram", "Palakkad"],
"Goa": ["North Goa", "South Goa"],
},
"The United States of America": {
"califonia": ["California’s 34th congressional district", "California’s 38th congressional district"],
"Florida": ["Florida"]
}, "Canada": {
"Alberta": ["Acadia", "Bighorn"],
"Columbia": ["Washington DC"]
},
}
window.onload = function ()
{
var countySel = document.getElementById("countySel"),
stateSel = document.getElementById("stateSel"),
districtSel = document.getElementById("districtSel");
for (var country in stateObject)
{
countySel.options[countySel.options.length] = new Option(country, country);
}
countySel.onchange = function ()
{
stateSel.length = 1;
districtSel.length = 1;
if (this.selectedIndex < 1) return;
for (var state in stateObject[this.value])
{
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
countySel.onchange();
stateSel.onchange = function ()
{
districtSel.length = 1;
if (this.selectedIndex < 1) return;
var district = stateObject[countySel.value][this.value];
for (var i = 0; i < district.length; i++) {
districtSel.options[districtSel.options.length] = new Option(district[i], district[i]);
}
}
}
</script>
Function is not working properly. The Problem is which user is selected is not displaying or stored correctly.
<script LANGUAGE="JavaScript" type="text/javascript">
function display()
{
var j=document.getElementById("countySel").selectedIndex;
var k=document.getElementsByTagName("option")[j].value;
var l=document.getElementById("stateSel").selectedIndex;
var m=document.getElementsByTagName("option")[l].value;
var n=document.getElementById("districtSel").selectedIndex;
var o=document.getElementsByTagName("option")[n].value;
var siva=document.getElementById("sai");
var displaysetting=siva.style.display;
if (typeof(Storage) !== "undefined")
{
localStorage.setItem('country',k)
localStorage.setItem('state',m)
localStorage.setItem('district',o)
if(displaysetting == "block")
{
siva.style.display='none';
inputfields.style.display='block';
document.getElementById("country1").innerHTML=localStorage.getItem('country');
document.getElementById("state1").innerHTML=localStorage.getItem('state');
document.getElementById("district1").innerHTML=localStorage.getItem('district');
}
else
{
siva.style.display='block';
}
}
else
{
document.getElementById("name1").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>
</head>
<body>
<form class="container" id="sai" style="display: block;" >
<div class="row">
<div class="form-group col-4">
<label>Select Country:</label>
<select name="state" id="countySel" class="form-control" size="1">
<option value="" selected="selected" >Select Country</option>
</select>
</div>
<div class="form-group col-4">
<label>Select State:</label>
<select name="country" id="stateSel" class="form-control" size="1">
<option value="" selected="selected" >Please select Country first</option>
</select>
</div>
<div class="form-group col-4">
<label>Select District:</label>
<select name="district" id="districtSel" class="form-control" size="1">
<option value="" selected="selected">Please select State first</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-secondary" type="submit" value="submit" onclick="display()" style="width: 100px;">SUBMIT</button>
</div>
</div>
</form>
<div class="container" id="inputfields" style="margin-top: 15px; display: none;">
<div class="row">
<div class="col-6">
<div id="img" style="width: 350px; height: 350px;">
</div>
</div>
<div class="col-6">
<div> COUNTRY: <p id="country1"></p></div>
<div> STATE: <p id="state1"></p></div>
<div> DISTRICT: <p id="district1"></p></div>
</div>
</div>
</div>
</body>
I tried a lot but i didn't found where i done mistake. Can any please sort out this problem.
You can modify your display() function like this:
let selectedCountryIndex=document.getElementById("countySel").selectedIndex;
let selectedStateIndex=document.getElementById("stateSel").selectedIndex;
let selectedDistrictIndex=document.getElementById("districtSel").selectedIndex;
let opt1 = document.getElementById("countySel").options[selectedCountryIndex].value;
let opt2 = document.getElementById("stateSel").options[selectedStateIndex].value;
let opt3 = document.getElementById("districtSel").options[selectedDistrictIndex].value;

javascript appendChild show the list item then make it disappear

<div id="task-list"> <!-- Table that show tasks -->
<ul id="list"> <!--Blank table that uses JavaScript to add tasks -->
</ul>
<input type="image" src="image/plus.svg" class="add-btn-hidden" onclick="addButton()" >
</div>
<div id="hidden-add-form">
<form>
<h2 id="form-header">Add New Task</h2>
<button id="cancel" onclick="cancelButton()">X</button>
<br>Name<br>
<input type="text" id="task-name"><br>
<div class="same-line-input">
<span id="place">Place</span> <span id="department">Department</span><br>
<input type="text" id="task-place">
<select id="select">
<option value="Blank"></option>
<option value="Cleanning">Cleaning</option>
<option value="Kitchen">Kitchen</option>
<option value="Receptionist">Receptionist</option>
<option value="Beltboy">Bellboy</option>
<option value="All">All</option>
</select><br>
</div>
Description<br>
<textarea rows="10" cols="50" id="description"></textarea><br>
<input type="radio" name="urgent" value="other" id="urgent-btn"> Urgent<br>
Attachment:<br><input type="file" name="fileToUpload" id="fileToUpload"><br>
<input type="submit" id="form-submit" onclick="addTask ()">
</form>
</div>
Javascript:
function addButton (){
document.getElementById("hidden-add-form").style.visibility = "visible";
};
function cancelButton(){
document.getElementById("hidden-add-form").style.visibility= "hidden";
};
function addTask (){
let ul = document.getElementById("list");
let name = document.getElementById("task-name");
let place = document.getElementById("task-place");
let department = document.getElementById("select");
let description = document.getElementById("description");
let nameValue = "Name: " + name.value;
let li = document.createElement("li")
li.setAttribute("id", "task-on-list");
li.appendChild(document.createTextNode(nameValue));
ul.appendChild(li);
};
Functions addButton() and cancelButton() work fine but the addTask() function shows the new list-item real quick then the list item disappear. I wanted to pass the information from the form to show it in a list item of an unordered list. nameValue is just a part of my experiment

Categories