I have the code below and what it currently does is if the user types index.html it will bring the to index.html etc. But what I want is if they type in a file that doesn't exist it alerts them. For example, they type hi.html and hi.html doesn't exist, it will then alert them saying the file doesn't exist.
The code:
let btn = document.querySelector('.ex');
let inputPath = document.querySelector('.path');
// redirect to chosen path
btn.addEventListener('click', function() {
location.href = inputPath.value;
});
<input type='text' class='path' style="color: #222; background: white; padding: 5px; border-radius: 6px; border: none;">
<br><br><input type="submit" class="ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;" />
you'd have to check against your available files to see if it's there. For example,
let files = ['index.html', 'hello.html']
Then, in your event listener, you only allow valid files to reassign location.href. For the rest, you could send an alert. For example,
if (files.some((file) => file == inputPath.value)) {
location.href = inputPath.value
} else {
alert('Not a valid path.')
}
Related
I have reviewed tonnes of articles and all solutions only update the visually displayed value as opposed to the actual value within the input tag itself.
When I click on a button a modal appears with a text input to enter a code. We will call it input1
Upon entering the code and exiting the modal the button updates to the code entered and a hidden input value gets updated as well. However the actual tags value="" remains the same.
I have tried numerous ways but all seem to only update the visual and not the true value.
Here is what I have so far but it only updates the value you see in the browser not within the tag itself.
let promoModal = document.getElementById("promoModal");
let promoBtn = document.getElementById("promo");
let promoSpan = document.getElementsByClassName("promoClose")[0];
promoBtn.onclick = function() {
promoModal.style.display = "block";
}
promoSpan.onclick = function() {
promoModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == promoModal) {
promoModal.style.display = "none";
}
}
function updatePromo() {
let promoValue = document.getElementById("promo-value");
let producePromo = document.getElementById("promo");
let copyPromo = document.getElementById("promo-value-copy");
producePromo.innerHTML = promoValue.value;
copyPromo.innerHTML = promoValue.value;
}
/* THE MODAL */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
}
/* The Close Button */
.adultClose,
.promoClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<button id="promo" type="button" class="promo">
<span class="promoCode">Promo Code +</span>
</button>
<input type="hidden" id="promo-value-copy" value="test">
<!-- Promo Modal -->
<div id="promoModal" class="modal">
<div class="modal-content">
<span class="promoClose">×</span>
<input type="text" class="promo-value" id="promo-value" value="" placeholder="Promotional code" onchange="updatePromo()">
</div>
</div>
I stripped the styling to get to the meat and potatoes.
How can I update the actual value="test" to the new value using javascript?
The innerHTML is used for changing HTML content, so for instance you can use it for changing the content of a paragraph <p id="text-to-change"></p>.
To change the input value you can use the .value property of the object.
Try to change the following line copyPromo.innerHTML = promoValue.value; with copyPromo.value = promoValue.value;
You need to change the value like this:
document.getElementById("promo-value-copy").value = promoValue.value;
so going with Barmar's suggestion I was able to update my updatePromo function to both produce the value as well as update the DOM value.
Here is the updated function. I hope it helps the community.
function updatePromo() {
let promoValue = document.getElementById("promo-value");
let producePromo = document.getElementById("promo");
let copyPromo = document.getElementById("promo-value-copy");
producePromo.innerHTML = promoValue.value;
copyPromo.innerHTML = promoValue.value;
copyPromo.setAttribute("value", promoValue.value); // suggestion given by Barmar
}
I had to leave the other element as it adds the text after the form field which is actually needed for this project however typically would not be needed.
I would like to save input data from web application in the same web location where the .html file placed. The saved file should be over ride with the new data every time we click the button. Currently, code downloads file to local. How to place the file in the web location and it should be over ride with new data?
Code:
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button]{
font: 17px Calibri;
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<!--Add few elements to the form-->
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</div>
</body>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
// This variable stores all the data.
let data =
'\r Name: ' + name.value + ' \r\n '
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.txt'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
</script>
</html>
Javascript doesn't allow save or read files locally without user's consent (aka download/upload). If you need store data for your website/application, you can use WebStorage instead.
What i exactly want to do is as follows:
I want to allow the user to add the number of rows he desires and fill information in them. After he clicks the submit button the data entered in the table should be processed by flask. How do i fetch the custom table from client side into my server . Answers with code demo appreciated( I am beginner hence).
Here is an example of a table with three columns, and the user can dynamically adds as many rows as needed, and then when submit button gets clicked we collect the data and send them to the server, here is the client side code, I made some styles to make it look well.
$("#add_rows").click(function() {
// each click on the `+` button adds a row to the table
$("#data_container tbody").append(`<tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>`);
});
$("#submit_rows").click(function() {
// `obj` for storing the inputs, and the `n` to make unrepeated keys
var obj = {}, n = 0;
// loop over the rows
$("#data_container tbody tr").each(function(ind, tr) {
// add an array to the object
obj[`r${n}`] = [];
// loop over the inputs of this row
$(this).find("input").each(function(ind, input) {
// add the value of the input to the array and make sure to remove any semicolon since
// we will use it to separate the inputs
var val = input.value.replace(/;/g, "");
obj[`r${n}`].push(val);
});
// no need for the array, just join it to a string of values separated by semicolons
obj[`r${n}`] = obj[`r${n}`].join(";");
// increase the value of `n`
n++;
});
// log the object to the console so you can see what we are sending
console.log(obj);
// send the data to the server, see the console for a logging message for success
$.post("http://127.0.0.1:3000", obj, (data, status) => console.log("Status: " + status));
});
* {
box-sizing: border-box;
}
#data_container {
border: 1px solid green;
width: 500px;
border-radius: 5px;
padding: 3px;
background: radial-gradient(lightgreen, green);
position: relative;
font-family: monospace;
font-size: 24px;
}
#data_container th {
background-color: lightgreen;
color: white;
border-radius: 5px 5px 0 0;
}
#data_container td, th {
width: 33%;
height: 40px;
border: 1px solid green;
}
#data_container input {
width: 100%;
height: 100%;
border-color: #aaa;
font-size: 24px;
}
#add_rows, #submit_rows {
height: 50px;
position: absolute;
background-color: lightgreen;
font-weight: bold;
cursor: pointer;
outline: none;
font-size: 24px;
display: flex;
justify-content: center;
align-items: center;
color: yellow;
}
#add_rows {
width: 50px;
bottom: -25px;
right: -25px;
border-radius: 50%;
font-size: 48px;
}
#submit_rows {
width: 100%;
bottom: -30px;
left: 0;
border-bottom-left-radius: 50%;
z-index: -1;
font-variant: small-caps;
letter-spacing: 10px;
align-items: flex-end;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data_container">
<form>
<table>
<thead>
<tr><th>Name</th><th>Job</th><th>Country</th></tr>
</thead>
<tbody>
<tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>
</tbody>
</table>
</form>
<button id="submit_rows">Submit</button>
<button id="add_rows">+</button>
</div>
And here is the backend code, since you use Flask, I did the same
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def get_table_data():
# if the method is POST then the user is submitting a form otherwise he's just requesting the rendered document page
if request.method == "POST":
print("Posting data")
for input in request.form:
row = request.form[input].split(";")
print("--------------------------")
print("Name: " + row[0]);
print("Job: " + row[1]);
print("Country " + row[2]);
# I'm just printing it but you can do whatever you want with the data
# always the same page only for testing
return render_template("Table_send.html")
app.run(host = '127.0.0.1', port = 3000, debug = False)
If you are not familiar with Flask then you need to know these:
create a folder named "templates" in the same directory with the python script for server
run the script normally for example python server.py no need for Flask run ... and environment variable adding...
keep learning and happy coding :)
Test with three rows on client side
Getting data on backend side and printing'em out
Posting data
--------------------------
Name: Bobby
Job: Programmer
Country Canada
--------------------------
Name: Maria
Job: Designer
Country USA
--------------------------
Name: Michael
Job: Instructor
Country Germany
How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable
I'm trying to make it so that you can:
(achieved) 1. enter a url into the input form
2. add a prefix and postfix of my choice to the url (prefix = "http://"; postfix = "/postfixtexthere")
3. load the complete url (or value 'urlToLoad') into a web browser
I'm not sure if the variable 'urlToLoad' is correct or not because the 2nd alert doesn't work despite the 1st alert working.
My questions are as follows:
1. Is the variable 'urlToLoad' correct? Does it adapt to what's entered in the input box?
2. How can I then get the variable 'urlToLoad' to load as a website in a web browser?
Hopefully I've done most of the work already. Thanks for the advice.
function checkDomain() {
alert('function executed successfully');
var testInput = document.getElementById("checker");
var testUrl = textInput.value;
var urlToLoad = "http://" + testUrl + "/postfixtexthere";
alert(urlToLoad);
// instructions
// var urlToLoad = PUT VAR ‘testUrl’ INTO THIS URL, REPLACING ‘__________’: http://__________/postfixtexthere
// THEN LOAD THE URL AS A LINK IN A WEB BROWSER
}
.cta-button, a.cta-button {
border-radius: 6px;
padding: 10px 20px;
border: 1px solid #393939;
cursor: pointer;
background: #ff0;
display: inline-block;
text-align: center;
}
<p>text above the input type</p>
<div id="misc">
<input type="text" placeholder="Enter url" id="checker" value="thisdomain">
</div>
<a class="cta-button" onclick="checkDomain()">Check Link</a>
Try to run this in your local and it should open the URL in new window
function checkDomain() {
alert('function executed successfully');
var testInput = document.getElementById("checker");
var testUrl = document.getElementById('checker').value;
var urlToLoad = "https://" + testUrl + "/postfixtexthere";
alert(urlToLoad);
window.open(urlToLoad);
// instructions
// var urlToLoad = PUT VAR ‘testUrl’ INTO THIS URL, REPLACING ‘__________’: http://__________/postfixtexthere
// THEN LOAD THE URL AS A LINK IN A WEB BROWSER
}
.cta-button, a.cta-button {
border-radius: 6px;
padding: 10px 20px;
border: 1px solid #393939;
cursor: pointer;
background: #ff0;
display: inline-block;
text-align: center;
}
<p>text above the input type</p>
<div id="misc">
<input type="text" placeholder="Enter url" id="checker" value="thisdomain">
</div>
<a class="cta-button" onclick="checkDomain()">Check Link</a>