How to properly remove the contents inside of a modal - javascript

The heights of each building from West (left) to East (right) is given in an integer array. You have to tell which buildings will be able to see the sunset. I've written a program that will be able to tell which buildings can view the sun from left to right. The problem I'm having is currently with the modal. I'm trying to clear the information that is inside the modal use clearContents(). At first, I was using clear() till i noticed that clear() is a global method. I then tried using document.getElementById("results").innerHTML = " ";.
the entire website is provided but the code snippet is below.
https://zacharyhadjahsunsethills.netlify.app/
let sunsetOrder = ["Building 1 will always view the sunset!"];
function BeginFunction(){
//wire up all the data to the building variables
let building1 = parseInt( document.getElementById("input1").value )
let building2 = parseInt( document.getElementById("input2").value )
let building3 = parseInt( document.getElementById("input3").value )
let building4 = parseInt( document.getElementById("input4").value )
let building5 = parseInt( document.getElementById("input5").value )
//User Input validation
if(building1 == null || building2 == null || building3 == null || building4 == null ||
building5 == null){
document.getElementById("results").innerHTML = `You must input numbers for all buildings`
//clear data
document.getElementById("results").innerHTML = ``
}else{
//Put all the buildings into an array
let buildingsArray = [building1, building2, building3, building4, building5]
//You will need to use nested for loops. Nested for loops are how you can properly
//compare elements inside of an array with eachother.
//Loop starts at one because it will be the loop that is compared to all the
//previous buildings that are infront of it
for (let currentBuilding = 1; currentBuilding < buildingsArray.length; currentBuilding++) {
//will be kept false UNTIL you find the tallest building
//once tallest building is found, it will be switched to true
let tallest = false;
//this loop starts at one because it will need to stay before the position of the
//current building. It needs to stay before current building to properly compare
//which building is taller. That is why the middle condition is
// previousBuilding < currentBuilding
for (let previousBuilding = 0; previousBuilding < currentBuilding; previousBuilding++) {
//if any of the previous building are taller than the building that is currently being compared with,
//then change the bool to true
if(buildingsArray[previousBuilding] >= buildingsArray[currentBuilding]){
tallest = true;
break;
}else{
continue;
}
}
if(tallest == false){
sunsetOrder.push("Building #" +(currentBuilding + 1)+ " can view the sunset")
}
else{
sunsetOrder.push("Building #" +(currentBuilding + 1)+ " can't view the sunset")
}
let results = sunsetOrder.join("<br>")
document.getElementById("results").innerHTML = `${results}`
}
}
}
function clearContents(){
document.getElementById("results").innerHTML ="";
}
.navbar-dark .navbar-nav .active>.nav-link{
color:white;
}
.navbar-dark .navbar-nav .nav-link{
color:black;
}
.navbar .navbar-brand{
color:black;
}
.container {
width:960px;
height:640px;
position:absolute;
top:50%;
left:50%;
margin-top:-320px;
margin-left:-480px;
}
body{
background-image: url("img/SunsetHillsBackground.png");
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
::selection{
background-color: #F0E440;
}
#ResultsHeader{
background-color: #F0E440;
}
#ResultsFooter{
background-color: #F0E440;
}
#ResultsBody{
background-color:#f3eb7b
}
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fizz Buzz Coding Challenge (Implementing the Meta Strat</title>
<!-- Bootstrap 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="css/custom.css">
<link rel="stylesheet" href="css/prism.css">
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-dark" style="background-color: #F0E440;">
<a class="navbar-brand" href="index.html">SunsetHills</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId"
aria-expanded="false" aria-label="Toggle navigation"></button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item">
<a class="nav-link" href="index.html">πŸŒ’Home </a>
</li>
<li class="nav-item">
<a class="nav-link active" href="solve.html">πŸŒ“Solve <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="code.html">β˜€Code</a>
</li>
<li class="nav-item">
<a class="nav-link" target="_blank" href="https://zacharyhadjah.netlify.app/">πŸŒ—Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" target="_blank" href="https://github.com/zhadjah9559/SunsetHills">🌘Github</a>
</li>
</ul>
</div>
</nav>
<div class="container pt-5 align-items-center">
<div class="row justify-content-center pb-4">
<img src="img/SunsetHills.png" alt="Sunset Hills logo" id="Logo" class="responsive" >
</div>
<hr/>
<div class="row pt-5 mt-5">
<div class="col-md form-group">
<input class="form-control" id="input1" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input2" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input3" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input4" placeholder="Enter Height" type="number"/>
</div>
<div class="col-md form-group">
<input class="form-control" id="input5" placeholder="Enter Height" type="number"/>
</div>
</div>
<div class="row justify-content-center pt-2">
<label>
<button class="btn btn-primary" type="submit" onclick="BeginFunction()"
data-toggle="modal" data-target="#ResultsModal">
Submit
</button>
</label>
</div>
</div>
<!--Results Modal-->
<div class="modal fade" id="ResultsModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header justify-content-center" id="ResultsHeader">
<h1 id="ResultsHeaderH1">Results</h1>
</div>
<div class="modal-body" id="ResultsBody">
<div id="small-dialog2" class="white-popup zoom-anim-dialog text-center">
<div id=results></div>
</div>
</div>
<div class="modal-footer justify-content-center" id="ResultsFooter">
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="clearContents()">Close</button>
</div>
</div>
</div>
</div>
<!--Results Modal-->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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="js/custom.js"></script>
<script src="js/prism.js"></script>
</body>
</html>

If you inspect the content of the web with the devs tools you can see that your function clearContents() is working correctly.
The problem here is that you ain't clearing your sunsetOrder array, so every time that you do click on the submit button you are pushing new elements to it and showing all the array in the modal.
To solve this you can add the following code to your clearContents function:
function clearContents() {
document.getElementById("results").innerHTML ="";
sunsetOrder = [];
}

Related

Why does my delete button does not delete the card

I want to delete the card when we click on the delete button after adding a TODO note
I have created a website which uses localstorage to store notes and display when clicking the create TODO button and it all works but when I click the delete button after the note is created (You have to create a TODO first) it does not delete the div itself
I want to delete the card when we click on the delete button
CODE:
<!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>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
if (key != "" && value != "") {
iHTML = ""
localStorage.setItem(key, value)
iHTML += `
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${key}</h5>
<p class="card-text">${localStorage.getItem(key)}</p>
<button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
</div>
</div>
`
document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>
The error is thrown on this line onclick='${key}.innerHTML=""'. You will want to first remove the item from local storage e.g: localStorage.removeItem('${key}') and then remove the html. Theres many way of achieveing this but this.parentElement.parentElement.remove() should be sufficient
The complete button should look something like <button type="button" id="note" onclick="localStorage.removeItem('${key}'); this.parentElement.parentElement.remove()" class="btn btn-danger '${key}'">Delete</button>
Heres a working example:
https://jsfiddle.net/qt83bshd/
Well, i post you a simple solution for your problem.
Instead of use innerhtml to introuce your todos, yo can create the elements.
<!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>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
/* add css in this poiint to optimize code*/
.card {
width: 18rem;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
// collect the div that contains all the todos
let alltodo = document.querySelector(".all-todo");
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
// and if it any todo create the card
if (key != "" && value != "") {
localStorage.setItem(key, value)
// with create element we can create the card more easy
var todo = document.createElement("div");
todo.setAttribute("class", "card");
var button = document.createElement("button");
button.textContent = "eliminar";
var titulo = document.createElement("h5");
titulo.textContent = key;
button.onclick = () => {
console.log(button.parentElement.remove())
// in this point we can also remove the todo from the local storage wih localstorage.removeItem()
}
// introduce all items in dom
todo.appendChild(titulo)
todo.appendChild(button);
alltodo.appendChild(todo);
// iHTML = ""
// localStorage.setItem(key, value)
// iHTML += `
// <div class="card" style="width: 18rem;">
// <div class="card-body">
// <h5 class="card-title">${key}</h5>
// <p class="card-text">${localStorage.getItem(key)}</p>
// <button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
// </div>
// </div>
// `
// document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>

how to clear search result while click in search button

I made a song and a lyric searching page. The first time search is working well but while I click in the search button the previous result remains and also search results also shown on the page.
Now I want to disappear the result while searching for another song or lyric.
And also I want to make the search the result same style but I don't get results as I wanted.
const text = document.getElementById('text');
const search = document.getElementById('search');
const result = document.getElementById('result');
// api url
const api= 'https://api.lyrics.ovh';
// song lyrics
function getLyrics (artist, title) {
let url = `${api}/v1/${artist}/${title}`
fetch(url)
.then(res => res.json())
.then(singerLyrics => {
const lyrics = singerLyrics.lyrics;
const getLyric = document.getElementById('getLyric');
getLyric.innerHTML = `<h2 class="text-success mb-4">${artist} - ${title}</h2>
<pre class="lyric text-white">${lyrics}</pre>`;
});
result.innerHTML= '';
}
// search by song or artist
function searchSongs(term){
fetch(`${api}/suggest/${term}`)
.then(res => res.json())
.then (showData);
};
// search result
function showData (data) {
result.innerHTML = `<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9"> ${data.data.map(song => `<h3 class="lyrics-name">${song.title}</h3>
<p class="author lead">${song.type} by <span>${song.artist.name}</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button onclick="getLyrics('${song.artist.name}','${song.title}')" class="btn btn-success">Get Lyrics</button>
</div>
</div>`)};
`;
};
//event listeners
search.addEventListener('click', function searchResult (){
const inputText = text.value.trim();
if (!inputText){
alert('this is not a song or artist')
}else {
searchSongs(inputText);
}
});
body{
background-color: #13141b;
color: #ffffff;
background-image: url(images/bg-image.png);
background-repeat: no-repeat;
background-size: 100%;
background-position: top;
}
.form-control{
background-color:rgba(255, 255, 255, 0.2);
padding: 22px;
border: none;
border-radius: 25px;
}
.btn{
border-radius: 1.5rem;
padding: 9px 20px;
}
.btn-privious{
background: rgba(255, 255, 255, 0.2);
color: #ffffff;
}
.navbar-toggler {
border: none;
}
.search-box{
position: relative;
}
.search-btn {
position: absolute;
top: 0;
right: 0;
height: 100%;
}
.single-result{
background: rgba(255, 255, 255, 0.2);
border-radius: 15px;
}
<!doctype html>
<html lang="en">
<head>
<title>Hard Rock Solution - Song Lyric App</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- Custom css -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-dark my-3">
<a class="navbar-brand" href="#">
<img src="images/logo.png" alt="Hard Rock Solution">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<img src="images/toggler-icon.svg" alt="">
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdownId">
<a class="dropdown-item" href="#">Action 1</a>
<a class="dropdown-item" href="#">Action 2</a>
</div>
</li>
</ul>
</div>
</nav>
<main class="content-area">
<div class="search-bar col-md-6 mx-auto">
<h1 class="text-center">Lyrics Search</h1>
<div class="search-box my-5">
<input id="text" type="text" class="form-control" placeholder="Enter your artist song name">
<button id="search" class="btn btn-success search-btn">Search</button>
</div>
</div>
<!-- === Simple results === -->
<div class="d-flex justify-content-center">
<div id="result" class="">
</div>
<!-- Single Lyrics -->
<div id="getLyric" id="artistTitle" class="single-lyrics text-center">
</div>
</div>
</main>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Custom Script Here -->
<script src ="javascrpt.js"> </script>
</body>
</html>
try to use autocomplete="off" like
<input type="text" name="foo" autocomplete="off" />
Every time, search is clicked, the lyrics container should be emtpied:
document.querySelector("#getLyric").childNodes.forEach(el => el.remove())
to fix the issue, add this to your script:
document.querySelector("#search").addEventListener('click', function () {
document.querySelector("#getLyric").innerHTML = '';
})

Bootstrap modal window won't open because of interference with other elements

I can't seem to figure out why bootstrap's modal window isn't popping up.
I've looking into other similar questions and I still can't get it to work.
I've tried the process of elimination and try to eliminate all my scripts (except the bootstrap script) and it still won't open. Same with my CSS files. I also had inputted manual code for a modal window (before I incorporated bootstrap) so I was worried that the id="modal" from other modals would interfere. I deleted those too and nothing worked.
Here is my codepen, I've commented the sections the modal window code starts: https://codepen.io/eylenkim/pen/KKwMPLm
HTML:
<!--
-- fix other <a> tags // fix navigation
--fix "exit" for contact pop up (mobile)
-- center the Contact dialog box on viewport in mobile
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Art By Eylen | Shop</title>
<meta name="description" content="Browse Eylen's art portfolio to view work created with 35mm photography, blockprinting, and acrylic.">
<meta name="author" content="Eylen Kim">
<!-- data-src
––––––––––––––––––––––––––––––––––––––––––––––––––- -->
<link href="subpage-stylesheet.css" rel=stylesheet type="text/css">
<link href="StyleSheet.css" rel=stylesheet type="text/css">
<link href="skeleton.css" rel=stylesheet type="text/css">
<link href="otherCss/normalize.css" rel="stylesheet" type="text/css">
<link href="otherCss/font-awesome.css" rel=stylesheet type="text/css">
<link href="bootstrap-4.3.1-dist/css/bootstrap.css" rel=stylesheet type="text/css">
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet" type="text/css">
<!-- Mobile Meta
––––––––––––––––––––––––––––––––––––––––––––––––––-->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- Favicon
––––––––––––––––––––––––––––––––––––––––––––––––––-->
<link rel="icon" type="image/png" href="photo/favicon1.png" />
</head>
<!-- Menu // Hamburger Bar
––––––––––––––––––––––––––––––––––––––––––––––––––-->
<nav class="navigation">
<a href="#" class="menu-icon">
<i class="fa fa-bars"></i>
</a>
<ul class="main-navigation" role="navigation">
<div id="nav-x" class="menu-icon">&Cross;</div>
<li>
<div href="index.html">
Home</a>
</li>
<li>
<div href="portfolio.html">
Portfolio</a>
</li>
<li>
<div class="trigger" style="height: 100%;padding: 10px 0 10px 10px;">
About Me
<div class="modal">
<div class="modal-content" style="height: 95%; max-height: 600px;padding: 2rem 4.6rem;">
<span class="close-button">Γ—</span>
<h3>
Hello,<br>I'm Eylen!
</h3>
<img id="about-me-pic" src="photo/meee.JPG">
<p style="font-size: .75em; height: 44.3%; padding-top: 15px;">This art website is my passion project. I have coded my own platform to showcase & sell my art. What a treat to have you here on this site!<br><br> The mediums I work with: 35mm film photography, acrylic (canvas & glass), polymer clay (earrings), and printmaking.
<br><br>
In my free time I like petting my cat, tickling some gnarly tunes on the bass/electric guitar, coding, playing video games, and doing art stuff.<br><br>
</p>
</div>
</div>
</div>
</li>
<li style="height: 100%;padding: 20px 0 10px 7px;">
<p class="about-me-desktop" onclick="document.getElementById('id01').style.display='block'" style="position: relative;top: -3px;">Contact
</p>
<div class="w3-container">
<div id="id01" class="w3-modal">
<div class="modal-content-contact-portfolio">
<span class="close-button" onclick="document.getElementById('id01').style.display='none'" >Γ—</span>
<h3 style="margin-bottom: 0px;">
Contact Me
</h3>
<p>
<div class="contact-us-form" style="font-size: .7em;">
<form action="https://formspree.io/eylenkim#gmail.com" method="POST">
<div class="row" style="z-index: 9999999;">
<div class="six columns">
<input class="u-full-width" type="text" placeholder="Name" id="nameInput" name="Name" requiprintmaking>
</div>
<div class="six columns">
<input class="u-full-width" type="email" placeholder="Email" id="emailInput" name="Email" requiprintmaking>
</div>
</div>
<textarea class="u-full-width" placeholder="Message" id="messageInput" name="Message" requiprintmaking style="height: 160px;margin-top: 20px;line-height: 17px;padding-top: 8px;"></textarea>
<input class="button u-pull-right" type="submit" value="Send" style="color: black;"><br><br><br>
</form>
</div>
</p>
</div>
</div>
</div>
</li>
</ul>
</nav>
<header>
<div class="container fade-in">
<div class="row">
<a href="index.html">
<h1 class="one-third column u-pull-left">Art By <span><br></span><span id="h1-title-span"> Eylen</span></h1>
</a>
<h2 class="one-third column u-pull-left" id="portfolio-title-desktop">| Shop</h2>
<h2 class="one-third column u-pull-left" id="portfolio-title-mobile">
<span>&boxh;&boxh;<br></span>Shop
</h2>
<div class="about-contact-text" class="one-third column u-pull-right">
<a href="index.html">
<p class="about-me-desktop">Home</p>
</a>
<span class="trigger">
<p class="about-me-desktop">
About Me
</p>
<div class="modal">
<div class="modal-content">
<span class="close-button">Γ—</span>
<h3>
Hello,<br>I'm Eylen!
</h3>
<img id="about-me-pic" src="photo/meee.JPG">
<p>This art website is my passion project. I have coded my own platform to showcase & sell my art. What a treat to have you here on this site!<br><br> The mediums I work with: 35mm film photography, acrylic (canvas & glass), polymer clay (earrings), and printmaking.
<br><br>
In my free time I like petting my cat, tickling some gnarly tunes on the bass/electric guitar, coding, playing video games, and doing art stuff.<br><br>
</p>
</div>
</div>
</span>
<p class="about-me-desktop" onclick="document.getElementById('id02').style.display='block'">
Contact
</p>
<div class="w3-container">
<div id="id02" class="w3-modal">
<div class="modal-content-contact">
<span class="close-button" onclick="document.getElementById('id02').style.display='none'" >Γ—</span>
<h3 style="margin-bottom: 0px;">
Contact Me
</h3>
<p>
<div class="contact-us-form">
<form action="https://formspree.io/eylenkim#gmail.com" method="POST">
<div class="overlap-text">
<div class="overlap-text-base-contact">
<h2 class="load two-thirds column">Contact</h2>
</div>
</div>
<div class="row" style="z-index: 9999999;">
<div class="six columns">
<input class="u-full-width" type="text" placeholder="Name" id="nameInput" name="Name" required>
</div>
<div class="six columns">
<input class="u-full-width" type="email" placeholder="Email" id="emailInput" name="Email" required>
</div>
</div>
<br>
<textarea class="u-full-width" placeholder="Message" id="messageInput" name="Message" required style=" height: 100px;
margin-top: 10px;
line-height: 17px;
padding-top: 8px;"></textarea>
<br><br>
<input class="button u-pull-right" type="submit" value="Send"><br><br><br>
</form>
</div>
</p>
</div>
</div>
</div>
</div>
</div>
</header>
<body class="top" id="top">
<section class="grid-wrapper">
<div class="filter-controls">
<div class="control fade-in">Filter By:
<select class="filter-field form-control">
<option value="">None</option>
<option value="prints">Prints</option>
<option value="earrings">Earrings</option>
<option value="commissions">Commisions</option>
</select>
</div>
</div>
<div class="grid bootstrap-on fade-in" style="flex-direction: row !important;">
<!------ Product w/ Carousel ---------------------------------------------------------------------->
<div class="card item" data-color="earrings">
<div class="price-tag">$10</div>
<div id="earrings1" class="carousel slide" data-interval="false">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="image" class="d-block w-100 crop-shp" alt="...">
</div>
<div class="carousel-item">
<img src="image" class="d-block w-100 crop-shop" alt="...">
</div>
</div>
<a class="carousel-control-prev" href="#earrings1" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#earrings1" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="card-body">
<h5 class="card-title">Carousel</h5>
<p class="card-text">I want to potentially add the ability to click on the carousel images for the pop up modal</p>
</div>
</div>
<!------ Product w/ Modal Window ---------------------------------------------------------------------->
<div class="card item" data-color="prints">
<div class="price-tag" data-toggle="modal" data-target="#exampleModal">$10</div>
<img src="image" class="card-img-top crop-shop" alt="Print" data-toggle="modal" data-target="#exampleModal">
<div class="card-body">
<h5 class="card-title">(Modal Window)</h5>
<p class="card-text">I want the modal window to pop up when clickin on the image</p>
</div>
</div>
</div>
<!-- Modal ------------------------------------------------------------------------------------>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Cute Earrings</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">Γ—</span>
</button>
</div>
<div class="modal-body">
<p>THIS IS THE MODAL!</p>
Buy
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</select>
</section>
<!----- Muuri Filtering ----->
<script>
document.addEventListener('DOMContentLoaded', function () {
var grid = null,
wrapper = document.querySelector('.grid-wrapper'),
searchField = wrapper.querySelector('.search-field'),
filterField = wrapper.querySelector('.filter-field'),
sortField = wrapper.querySelector('.sort-field'),
gridElem = wrapper.querySelector('.grid'),
searchAttr = 'data-title',
filterAttr = 'data-color',
searchFieldValue,
filterFieldValue,
sortFieldValue,
dragOrder = [];
// Init the grid layout
grid = new Muuri(gridElem, {
dragEnabled: false,
layout: {
fillGaps: true
}
});
// Filter field event binding
filterField.addEventListener('change', filter);
// Sort field event binding
sortField.addEventListener('change', sort);
// Filtering
function filter() {
filterFieldValue = filterField.value;
grid.filter(function (item) {
var element = item.getElement(),
isSearchMatch = !searchFieldValue ? true : (element.getAttribute(searchAttr) || '').toLowerCase().indexOf(searchFieldValue) > -1,
isFilterMatch = !filterFieldValue ? true : (element.getAttribute(filterAttr) || '') === filterFieldValue;
return isSearchMatch && isFilterMatch;
});
}
});
</script>
<script src="js/muuri.js"></script>
<script src="https://unpkg.com/web-animations-js#2.3.2/web-animations.min.js"></script>
<!--Modal - Dialog Boxes -->
<script type="text/javascript"> const modals = Array.from(document.querySelectorAll('.modal'));
const triggers = Array.from(document.querySelectorAll('.trigger'));
var closeButton = document.querySelector(".close-button");
//if a trigger is clicked then...
for (const trigger of triggers) {
trigger.addEventListener('click', toggleModal);
}
// .. then toggle it's modal
function toggleModal(event) { event.target.closest('.trigger').querySelector('.modal').classList.toggle("show-modal"); }
// check if the clicked element is a modal, or in a modal
function windowOnClick(event) {
if (modals.some((modal) => modal.contains(event.target))) {
toggleModal();
}
}
</script>
<script>
function closeButton() {
document.getElementByClass('id02').style.display='none'
}
</script>
<!----- JS files ----->
<script type="text/javascript" src="js/scripts.js"></script>
<script type="text/javascript" src="js/singlenav.js"></script>
<script type="text/javascript" src="js/scrollreveal.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload#12.4.0/dist/lazyload.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></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>
<i class="icon-chevron-up"></i>
<!----- Lazy Load ----->
<script>
(function() {
function logElementEvent(eventName, element) {
console.log(
Date.now(),
eventName,
element.getAttribute("data-src")
);
}
var callback_enter = function(element) {
logElementEvent("πŸ”‘ ENTERED", element);
};
var callback_exit = function(element) {
logElementEvent("πŸšͺ EXITED", element);
};
var callback_reveal = function(element) {
logElementEvent("πŸ‘οΈ REVEALED", element);
};
var callback_loaded = function(element) {
logElementEvent("πŸ‘ LOADED", element);
};
var callback_error = function(element) {
logElementEvent("πŸ’€ ERROR", element);
element.src =
"https://via.placeholder.com/440x560/?text=Error+Placeholder";
};
var callback_finish = function() {
logElementEvent("βœ”οΈ FINISHED", document.documentElement);
};
ll = new LazyLoad({
elements_selector: ".lazy",
load_delay: 300,
threshold: 0,
// Assign the callbacks defined above
callback_enter: callback_enter,
callback_exit: callback_exit,
callback_reveal: callback_reveal,
callback_loaded: callback_loaded,
callback_error: callback_error,
callback_finish: callback_finish
});
})();
</script>
<!----- Scroll To Top ----->
<script>
$(window).scroll(function() {
if ($(this).scrollTop() >= 600) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(200); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(200); // Else fade out the arrow
}
});
$('#return-to-top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop : 0 // Scroll to top of body
}, 500);
});
</script>
</body>
</html>
There are 2 separate issues that are preventing the modal from showing up.
1) The first issue is with your code
The bootstrap library you use returns 404.
How to check if it's happening for you?
Open your browser's inspector, and press CTRL+SHIFT+I
You will see:
Failed to load resource: the server responded with a status of 404 () eylenkim/fullpage/bootstrap-4.3.1-dist/css/bootstrap.css
In fact, this happens for a lot of your relative URLs.
Solution
Replace links to Bootstrap libraries with working ones, eg. from https://getbootstrap.com/
The ones I used in my testing of your code:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
See gist for minimum code sample for a modal here: https://codepen.io/edwin-chua/pen/rNaLOEg
Once you fix the link problem, you will run into the second issue.
2) The second issue is with your stylesheet
Once you fixed your code as I suggested, you get a dark overlay with no modal.
Removing the reference to https://eylenkim.github.io/ArtByEylen/StyleSheet.css allows the modal to show up, so something in here is interfering with the modal's css.
Here is a working pen: https://codepen.io/edwin-chua/pen/QWwEyyZ
Separate Problem
You seem to have imported some libraries twice, once in the Codepen UI, and once in the HTML file. This will cause you debugging headaches. Make sure you only import them once. Since you are building an entire webpage, I suggest putting all of it in the HTML file.
also see JS tab
And
Further Comments
This section of code seems to be for closing the modal? If so, it probably isn't required, as Bootstrap automatically binds the click events.
<!--Modal - Dialog Boxes -->
<script type="text/javascript"> const modals = Array.from(document.querySelectorAll('.modal'));
const triggers = Array.from(document.querySelectorAll('.trigger'));
var closeButton = document.querySelector(".close-button");
//if a trigger is clicked then...
for (const trigger of triggers) {
trigger.addEventListener('click', toggleModal);
}
// .. then toggle it's modal
function toggleModal(event) { event.target.closest('.trigger').querySelector('.modal').classList.toggle("show-modal"); }
// check if the clicked element is a modal, or in a modal
function windowOnClick(event) {
if (modals.some((modal) => modal.contains(event.target))) {
toggleModal();
}
}
</script>

How to fix input issue in CodeMirror

I'm trying to get code mirror to read and display the contents of a file into the textarea, but everytime I load a file, it prints the contents as one line, ignoring all line breaks, and if I try to manually enter text into the text field, it automatically tabs every line after the first.
Proper text form file format:
Proper textarea styling:
Unfortunate result of selecting a file (this text format won't function with the compile button):
Full HTML code (with suggested edits; still not working):
<!DOCTYPE html>
<html lang="en_US">
<head>
<title>Phoenix - UMSL's Online Assembly Code Compiler</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1 shrink-to-fit=no" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" 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.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="codemirror/lib/codemirror.js"></script>
<link rel="stylesheet" href="codemirror/lib/codemirror.css">
<link rel="stylesheet" href="codemirror/theme/colorforth.css">
<script src="codemirror/mode/javascript/javascript.js"></script>
<script src="codemirror/mode/cobol/cobol.js"></script>
<link rel="stylesheet" href="CSS/styling.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.min.css">
</head>
<body>
<fieldset>
<!-- Form Name -->
<nav class="navbar navbar-expand-lg navbar-expand-lg" style="border-bottom: 5px solid white;">
<a class="navbar-brand" href="./homepage.html"> <img src="IMGS/phoenix-small.png">PHOENIX</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="./homepage.html">Home</a>
<a class="dropdown-item" href="./reference.html">Reference</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="./about.html">About Team Phoenix</a>
</div>
</li>
</ul>
</div>
<a style="color:white;">UMSL's Online Assembly Code Compiler</a>
</nav>
<div class="WORKPLEASE" style="max-width: 98%;">
</br>
</br>
</br>
</br>
</br>
<!-- File Button -->
<div class="form-group">
<label class="row justify-content-md-center" for="filebutton" style="font-size: 40px">Choose a file to compile: </br></label>
<div class="row justify-content-md-center">
<input id="filebutton" name="filebutton" class="input-file" type="file">
<!--File Upload Script -->
<script type="text/javascript" src="fileUploadScript.js"></script>
</div>
</div>
</br>
<div class="row justify-content-md-center">
<p style="font-size: 40px;"> or... </br></p>
</div>
</br>
<!-- Textarea -->
<div class="form-group">
<label class="row justify-content-md-center" for="textarea" style="font-size: 40px">Write the file in the text field below: </br></label>
<div class="col-md-6 offset-md-3">
<div id="textarea" name="textarea" placeholder="Type your code here!" style="min-height: 250px; min-width: 100%; border-style: solid;"></div>
<script>
let editor = CodeMirror(document.getElementById("textarea"),{
lineNumbers: true,
mode: "cobol",
theme: "colorforth"
});
document.getElementById("filebutton").addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
editor.setValue(this.result); // Need to use the setValue method
//document.getElementById("textarea").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
</script>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="row justify-content-md-center" for="singlebutton"></label>
<div class="row justify-content-md-center">
<button id="textareabutton" name="singlebutton" class="btn btn-primary" onclick="main()" style="background-color:red; border-color:red;">Compile</button>
<script src="assmblyCode.js"></script>
</div>
</div>
</div>
</fieldset>
<!--<div id="footer">-->
<!--<p style="padding-top: 25px;">-->
<!--Β© Copyright 2019 Team Phoenix-->
<!--</p>-->
<!--</div>-->
</body>
</div>
The styling.css file:
/* Color assignment */
body {
background-image: url("../IMGS/binary.gif");
background-color: #cccccc;
}
.form-group{background-color:black;}
head {background-color: firebrick;}
h1 {color: blue}
h2 {color: snow}
nav {background-color: firebrick;}
a {color: snow;}
div {color: Azure}
/*italicizes and specifies which page you are on with color*/
a:hover{font-style: italic;}
/* alignment and font size */
head { font-size: 20pt}
h1 {text-align: center}
h2 {text-align: center}
h2 {font-size: 22pt}
.argname {font-size: 20px; text-decoration: underline; padding-top: 10px; background-color: black;}
.sides{ width:50%; float:left; padding-left: 20px}
.LI-profile-badge{
width:25%;
float:left;
padding-left: 20px;
}
#footer {
position: fixed;
bottom: 0;
width: 100%;
height: 70px;
background-color: black;
text-align: center;
}
The fileUploadScript.js used to load the file into the text area:
document.getElementById("filebutton").addEventListener('change', function () {
var fr = new FileReader();
fr.onload = function () {
document.getElementById("textarea").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
//https://www.youtube.com/watch?v=QI_NClLxnF0
Hopefully someone can spot what's being done wrong.
CodeMirror has several Content manipulation methods. You will need to use the setValue method.
doc.setValue(content: string)
Set the editor content.
Please reference the following block of code for my suggestions.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.min.css">
</head>
<body>
<!-- File Button -->
<div class="form-group">
<label class="row justify-content-md-center" for="filebutton" style="font-size: 40px">Choose a file to compile:</label>
<div class="row justify-content-md-center">
<input id="filebutton" name="filebutton" class="input-file" type="file">
</div>
</div>
<div class="row justify-content-md-center">
<p style="font-size: 40px;"> or...</p>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="row justify-content-md-center" for="textarea" style="font-size: 40px">Write the file in the text field below: </br>
</label>
<div class="col-md-6 offset-md-3">
<div id="textarea" name="textarea" placeholder="Type your code here!" style="min-height: 250px; min-width: 100%; border-style: solid; border-width: 1px; border-color: gray"></div>
<!-- This is where I think the problem is -->
<script>
let editor = CodeMirror(document.getElementById("textarea"), {
lineNumbers: true,
mode: "cobol",
theme: "colorforth"
});
document.getElementById("filebutton").addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
editor.setValue(this.result); // Need to use the setValue method
//document.getElementById("textarea").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
</script>
<!-- This is where I think the problem is -->
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="row justify-content-md-center" for="singlebutton"></label>
<div class="row justify-content-md-center">
<button id="textareabutton" name="singlebutton" class="btn btn-primary" onclick="main()" style="background-color:red; border-color:red;">Compile</button>
</div>
</div>
</body>
</html>
More specifically, editor.setValue(this.result); is what got it working. Take a look at this JS Bin
In your fileUploadScript.js you must use editor.setValue().
document.getElementById("filebutton").addEventListener('change', function () {
var fr = new FileReader();
fr.onload = function () {
editor.setValue(this.result);
//document.getElementById("textarea").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
You can't force the code into the textarea. It just won' work. You have to use the setValue method as shown above.
CodeMirror: Usage Manual.

How to prevent jquery submit button from refreshing the HTML page?

I have a login page where the user enters his username and password, when he submits this form the data is sent to php file for verifying the password.
For the first time when the user enters data (I entered wrong details) the page shows "Invalid password...please try again".
The second time when the user enters data (again I enter wrong details) the page just reloads. I am not able to understand why this is happening.
For more better understanding I have added a google drive link to a video showing the issue.
Link:Link to the video
The html code:
<!DOCTYPE html>
<html lang="en" xmlns:justify-content="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1 ">
<title>RVPS Elections</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark padding ">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">
<img src="assets/rv.png">
RV PUBLIC SCHOOL
</a>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="admin.html">Admin Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Contact Us</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<p align="center" class="lead">Get administrator access by entering correct details</p>
</div>
<div class="container-fluid padding mt-1 " style="align-items: center; justify-content:center; display:flex ;" >
<div class="row padding">
<div class="card border-dark" >
<div class="card-header" align="center">
<img src="assets/rv.png">
<h5>Admin Sign In</h5>
</div>
<div class="card-body" id="admin-signin-card">
<form id="admin-signin">
<div class="form-group">
<label>Username</label>
<input id="admin_username" type="text" class="form-control input-lg" placeholder="Enter your username" required>
</div>
<div class="form-group">
<label>Password</label>
<input id="admin_password" type="password" class="form-control input-lg" placeholder="Enter your Password" required>
</div>
<div class="form-group">
Forgot Password?
</div>
<div class="form-group" >
<input id="submit_button" type="submit" name="Sign In" value="Sign In" class="btn btn-success input-lg">
</div>
</form>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid padding">
<h1 align="center">About Us</h1>
<p align="center">I am Goutam B Seervi. A student of RVPS for the year 2015-18</p>
<h2 align="center">Contact me</h2>
<p align="center">Phone nnumber : 7019271367</p>
<p align="center">Email id : goutambseervi#gmail.com</p>
</div>
</footer>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="js/admin_login_script.js"></script>
</html>
The javascript part:
$(document).ready(function () {
$("#admin-signin").submit(function (e) {
e.preventDefault();
let admin_username = $("#admin_username").val();
let admin_password = $("#admin_password").val();
$.ajax({
url: 'php_admin_login.php',
data: {
admin_username: admin_username,
admin_password: admin_password
},
type: "POST",
dataType: "json",
success: function (response) {
if (response === "OK") {
window.open("admin.html", "_self");
}
else {
document.getElementById('admin-signin-card').innerHTML += '<div class="alert alert-danger"><h5>Error occured...Please try again</h5></div>';
console.log("error shown");
}
}
});
});
});
I'm sure there is no problem with the php code so I'm not pasting here just to make the question more clearer.
If you need the whole code of the project you can get it here:Github link to the project
else {
document.getElementById('admin-signin-card').innerHTML += '<div class="alert …>';
Adding to an element’s .innerHTML replaces the whole content of the element; even the stuff that was already there will first be removed, and then re-created.
So your form itself is replaced with a new form, and therefor you completely lose your submit event handler you had attached to it as well.
Your attempts at preventing the default event action fail, because you handler function simply doesn’t get called any more at all, and just a normal form submit is performed now, which of course reloads the page.
You need to either add your event handler again after you replaced the parent container’s innerHTML - or use event delegation to begin with.
Try to use this. Hope it will help
$("form").submit(function(e){
e.preventDefault();
});
Kindly let me know if it does not work.
Try return false at the end of your $("#admin-signin").submit function instead of the preventDefault()
This is happening due to how you handle errors. By using document.getElementById('admin-signin-card').innerHTML += ... you are effectively reloading your form meaning that you lose the event listener. You can either adjust how you display the error or adjust the event listener.
I would recommend changing how you display the error.
I have removed the request in the example below but it's the same idea:
$(document).ready(function () {
$("#admin-signin").submit(function (e) {
e.preventDefault();
let admin_username = $("#admin_username").val();
let admin_password = $("#admin_password").val();
let response = "no";
if (response === "OK") {
window.open("admin.html", "_self");
} else {
document.getElementById('admin-signin-card-error').innerHTML ='<div class="alert alert-danger"><h5>Error occured...Please try again</h5></div>';
console.log("error shown");
}
});
});
<!DOCTYPE html>
<html lang="en" xmlns:justify-content="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1 ">
<title>RVPS Elections</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark padding ">
<div class="container-fluid">
<a class="navbar-brand" href="index.html">
<img src="assets/rv.png"> RV PUBLIC SCHOOL
</a>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="admin.html">Admin Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Contact Us</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<p align="center" class="lead">Get administrator access by entering correct details</p>
</div>
<div class="container-fluid padding mt-1 " style="align-items: center; justify-content:center; display:flex ;">
<div class="row padding">
<div class="card border-dark">
<div class="card-header" align="center">
<img src="assets/rv.png">
<h5>Admin Sign In</h5>
</div>
<div class="card-body" id="admin-signin-card">
<form id="admin-signin">
<div class="form-group">
<label>Username</label>
<input id="admin_username" type="text" class="form-control input-lg" placeholder="Enter your username" required>
</div>
<div class="form-group">
<label>Password</label>
<input id="admin_password" type="password" class="form-control input-lg" placeholder="Enter your Password" required>
</div>
<div class="form-group">
Forgot Password?
</div>
<div class="form-group">
<input id="submit_button" type="submit" name="Sign In" value="Sign In" class="btn btn-success input-lg">
</div>
</form>
<div id="admin-signin-card-error"></div>
</div>
</div>
</div>
</div>
<footer>
<div class="container-fluid padding">
<h1 align="center">About Us</h1>
<p align="center">I am Goutam B Seervi. A student of RVPS for the year 2015-18</p>
<h2 align="center">Contact me</h2>
<p align="center">Phone nnumber : 7019271367</p>
<p align="center">Email id : goutambseervi#gmail.com</p>
</div>
</footer>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
</html>
like #CBroe mentioned, the problem is caused by innerHTML.
i moved the content of innerHTML to the form, and give it display none, when there an error i show the error with .show()
i changed the ajax url and data Type for testing purpose.
$(document).ready(function () {
$("#admin-signin").on('submit', function (event) {
event.preventDefault();
let admin_username = $("#admin_username").val();
let admin_password = $("#admin_password").val();
$.ajax({
url: 'https://jsonp.afeld.me/?url=https://jsonview.com/example.json',
type: "POST",
dataType: "jsonp",
data: {
admin_username: admin_username,
admin_password: admin_password
},
success: function (response) {
if (response === "OK") {
window.open("admin.html", "_self");
} else {
$('.alert.alert-danger').show();
console.log("error shown");
}
}
});
});
});
<!DOCTYPE html>
<html lang="en" xmlns:justify-content="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1 ">
<title>RVPS Elections</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid padding mt-1 " style="align-items: center; justify-content:center; display:flex ;" >
<div class="row padding">
<div class="card border-dark" >
<div class="card-header" align="center">
<h5>Admin Sign In</h5>
</div>
<div class="card-body" id="admin-signin-card">
<form id="admin-signin">
<div class="form-group">
<label>Username</label>
<input id="admin_username" type="text" class="form-control input-lg" placeholder="Enter your username" required>
</div>
<div class="form-group">
<label>Password</label>
<input id="admin_password" type="password" class="form-control input-lg" placeholder="Enter your Password" required>
</div>
<div class="form-group">
Forgot Password?
</div>
<div class="form-group" >
<input id="submit_button" type="submit" name="Sign In" value="Sign In" class="btn btn-success input-lg">
</div>
<div class="alert alert-danger" style="display: none;"><h5>Error occured...Please try again</h5></div>
</form>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
</body>
</html>

Categories

Resources