Changing the colour of the input field focus using JavaScript - javascript

I am implementing an HTML input field where the user has to enter his email address. I am also implementing validation on the same input field using JavaScript.
function validateEmail() {
var email = document.getElementById('EmailTextbox');
var errorMessage = document.getElementById('ErrorMessageJumbotron');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
errorMessage.style.display = 'block';
email.style.color = '#E54A49';
email.style.border = "1px solid #E54A49";
} else {
errorMessage.style.display = 'none';
email.style.border = "1px solid #949494";
email.style.color = 'black';
}
}
* {
font-family: 'Poppins', sans-serif;
}
#EmailTextbox {
margin-bottom: 15px;
}
input[type="text"] {
font-size: 1em;
height: 45px;
width: 100%;
border: 1px solid #949494;
}
<div class="container">
<div class="jumbotron" id="ErrorMessageJumbotron" style="display: none;">
<div id="errorMessage">
<i class="fa fa-exclamation-triangle fa-2x" aria-hidden="true">
<span style="font-family: 'Poppins', sans-serif; font-weight: 500;">Please correct the marked fields.</span>
</i>
</div>
</div>
</div>
<!--container-->
<div class="container jumbotron">
<input type="text" onblur="validateEmail()" id="EmailTextbox" placeholder="E-mail address" class="form-control">
</div>
If the email is incorrect, the border of the input field is set to red and the user is prompted to enter a valid email address. However, when the user clicks on the input field, the focus is coloured blue and I want it red for this particular case. Otherwise, I want it to be blue as the default.
I have tried several approaches to try to change the focus colour using JavaScript but I did not manage to get it working properly.

Here is a simplified version of what you are trying to do, to help you achieve your end goal:
HTML
<input onblur="onEmailInputBlur(event)" placeholder="E-mail address">
CSS
input.is-invalid {
border: 1px solid red;
outline: none;
}
JS
var invalidClass = 'is-invalid';
function onEmailInputBlur(event) {
var email = event.target.value,
elClassList = event.target.classList;
elClassList.remove(invalidClass);
if (!isEmailValid(email)) {
elClassList.add(invalidClass);
}
}
function isEmailValid(email) {
var validEmailRegex = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return validEmailRegex.test(email);
}
A JsFiddle example:
https://jsfiddle.net/ybaagysn/2/

Related

How to match user input with array data in JavaScript

I'm new in learning HTML, JavaScript and CSS. I'm stuck at this JavaScript code.
I'm trying to match user input on the searchbar with some city array list I already prepared, when the search result match the script will change the display style of element into showing the result of their search value, but until now the result always showing false value.
Is there any better way to do this? Is there something wrong with my code?
function searchRespond() {
if (document.getElementById("myInput").value.match(cities))
{
document.getElementById("areaCovered").style.display = "block";
}
else {
document.getElementById("areaNotCovered").style.display = "block";
document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value;
}
}
var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
.HeadlineSearchContainer {
position: relative;
top: 100px;
margin: auto;
height: 159px;
}
.SearchCharacterStyle {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
.searchrespond {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
#areaCovered {
display: none;
}
#areaNotCovered {
display: none;
}
#fillArea {
display: none;
}
<div class="HeadlineSearchContainer">
<div class="SearchCharacterStyle">
<h>SEARCH FOR AREA COVERANGE</h>
</div>
<div id="mySearch" class="searchbox_box">
<form autocomplete="off" name="myForm">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
<i class="searchbutton"></i>
</div>
<input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search">
<div class="searchrespond" id="searchRespond">
<h id="areaCovered">YES! We cover your area destination</h>
<h id="areaNotCovered">We don't cover your area destination yet
<p id="searchResult"></p>
</h>
<h id="fillArea">Please fill your area destination first</h>
</div>
</form>
</div>
</div>
To do what you require you can use filter() to match the user's input to values in your array. You would be best to perform a case-insensitive match, which can be done by converting both values to the same case.
Note that this logic sets the notifications as hidden before the logic runs, so that the previous state of the search is removed.
In addition, I made a couple of improvements to the code. Firstly I stored the relevant elements in variables instead of accessing the DOM every time. This is slightly more performant, and makes the code a lot easier to read. I also used addEventListener() to bind events instead of inline event handlers in the HTML, which are bad practice and shouldn't be used. Lastly I converted the <h> elements to <h2 /> in this demo, as there is no <h> element in HTML.
const input = document.querySelector('#myInput');
const areaCovered = document.querySelector('#areaCovered');
const areaNotCovered = document.querySelector('#areaNotCovered');
const searchResult = document.querySelector('#searchResult');
const fillArea = document.querySelector('#fillArea');
const cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
document.querySelector('#search-from').addEventListener('submit', e => {
e.preventDefault();
const searchTerm = input.value.trim().toLowerCase();
fillArea.style.display = 'none';
areaCovered.style.display = 'none';
areaNotCovered.style.display = 'none';
if (!searchTerm) {
fillArea.style.display = 'block';
return;
}
let matches = cities.filter(city => city.toLowerCase() == searchTerm);
if (matches.length) {
areaCovered.style.display = 'block';
} else {
areaNotCovered.style.display = 'block';
}
});
.HeadlineSearchContainer {
position: relative;
top: 100px;
margin: auto;
height: 159px;
}
.SearchCharacterStyle {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
.searchrespond {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
#areaCovered {
display: none;
}
#areaNotCovered {
display: none;
}
#fillArea {
display: none;
}
.autocomplete {
width: 300px;
}
<div class="HeadlineSearchContainer">
<div class="SearchCharacterStyle">
<h>SEARCH FOR AREA COVERANGE</h>
</div>
<div id="mySearch" class="searchbox_box">
<form autocomplete="off" name="myForm" id="search-from">
<div class="autocomplete">
<input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
<i class="searchbutton"></i>
</div>
<button type="submit">Search</button>
<div class="searchrespond" id="searchRespond">
<h2 id="areaCovered">YES! We cover your area destination</h2>
<h2 id="areaNotCovered">We don't cover your area destination yet</h2>
<h2 id="fillArea">Please fill your area destination first</h2>
</div>
</form>
</div>
</div>
You can use javascript includes().
<script>
const fruits = ["Banana Aceh", "Orange", "Apple", "Mango"];
let str = "Banana Aceh"; //document.getElementById("myInput").value
if(fruits.some(v => str.includes(v))) {
console.log("Exists");
} else {
console.log("Did not Exists");
}
</script>
function searchRespond() {
let searchTerm = document.getElementById("myInput").value;
if (cities.find(city => city == searchTerm))
{
document.getElementById("areaCovered").style.display = "block";
}
else {
document.getElementById("areaNotCovered").style.display = "block";
document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value;
}
}
var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
.HeadlineSearchContainer {
position: relative;
top: 100px;
margin: auto;
height: 159px;
}
.SearchCharacterStyle {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
.searchrespond {
font-family: Roboto;
font-size: 12px;
line-height: 24.82px;
text-align: left;
}
#areaCovered {
display: none;
}
#areaNotCovered {
display: none;
}
#fillArea {
display: none;
}
<div class="HeadlineSearchContainer">
<div class="SearchCharacterStyle">
<h>SEARCH FOR AREA COVERANGE</h>
</div>
<div id="mySearch" class="searchbox_box">
<form autocomplete="off" name="myForm">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="city" placeholder="Enter Your Destination City">
<i class="searchbutton"></i>
</div>
<input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search">
<div class="searchrespond" id="searchRespond">
<h id="areaCovered">YES! We cover your area destination</h>
<h id="areaNotCovered">We don't cover your area destination yet
<p id="searchResult"></p>
</h>
<h id="fillArea">Please fill your area destination first</h>
</div>
</form>
</div>
</div>
suggest to validate input by making first letter uppercase and rest lowercase to match the array values
with javascript indexOf function
function searchRespond() {
var input = document.getElementById("myInput").value;
var area2search = input.charAt(0).toUpperCase() + input.slice(1).toLowerCase(); /* make fist letter capital and rest lower case to match array */
if (cities.indexOf(area2search) > -1) {
document.getElementById("areaCovered").style.display = "block";
//In the array!
} else {
document.getElementById("areaNotCovered").style.display = "block";
document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value;
}
}
var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];

html not rendering properly on python flask site [duplicate]

This question already has an answer here:
Comments not working in jinja2
(1 answer)
Closed 2 years ago.
I've created a basic python flask site. I'm working on a signup page where I need to perform password complexity requirement checks. I figured the best way to do this might be with javascript on the client side instead of having to deal with Python code to handle this. I've created a signup.html page and a route within my python code but the page just loads as a blank white screen. Please help!
Here's my HTML signup page:
<!DOCTYPE html>
<!-- {% extends "base.html" %} -->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style all input fields */
input {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
}
/* Style the submit button */
input[type=submit] {
background-color: #4CAF50;
color: white;
}
/* Style the container for inputs */
.container {
background-color: #f1f1f1;
padding: 20px;
}
/* The message box is shown when the user clicks on the password field */
#message {
display:none;
background: #f1f1f1;
color: #000;
position: relative;
padding: 20px;
margin-top: 10px;
}
#message p {
padding: 10px 35px;
font-size: 18px;
}
/* Add a green text color and a checkmark when the requirements are right */
.valid {
color: green;
}
.valid:before {
position: relative;
left: -35px;
content: "✔";
}
/* Add a red text color and an "x" when the requirements are wrong */
.invalid {
color: red;
}
.invalid:before {
position: relative;
left: -35px;
content: "✖";
}
</style>
</head>
<body>
<h3>Password Validation</h3>
<p>Try to submit the form.</p>
<div class="container">
<form action="/action_page.php">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>
<label for="psw">Password</label>
<input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<input type="submit" value="Submit">
</form>
</div>
<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>
</body>
</html>
Here's my signup page python code:
#auth.route('/signup')
def signup():
return render_template('signup.html')
#auth.route('/signup', methods=['POST'])
def signup_post():
email = request.form.get('email')
name = request.form.get('name')
password = request.form.get('password')
# if re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[##$])[\w\d##$]{6,12}$", password):
user = User.query.filter_by(email=email).first() # check to see if user already exists
if user: # if a user is found, we want to redirect back to signup page so user can try again
flash('email address already exists')
return redirect(url_for('auth.signup'))
new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256'))
# add the new user to the database
db.session.add(new_user)
db.session.commit()
return redirect(url_for('auth.login'))
Few point to remember
Your signup.html must be inside templates directory
You can't <!-- {% extends "base.html" %} --> comment jinja template syntax like this, you can use like {# extends "base.html" #} this to ignore or remove the dead codes.

Javascript not creating spans as supposed to

I have a hardcoded span group to which I would like to add more spans from user input, I have tried to do this with a template and without but neither option works out for me
CSS:
.item { /*This is the style I want my new spans to inherit*/
display: flex;
align-items: center;
height: 48px;
line-height: 48px;
cursor: pointer;
padding-left: 24px;
}
.item:hover {
background-color: rgba(0, 0, 0, 0.04);
}
I'm trying to collect a user input from my modal to append it into my other spans which I hardcoded to see what it looks like for now
HTML:
<!------------------------------------------------------------- The modal from which i will be taking the input---------------------------------->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<form name="newLayerForm" onsubmit="return validateNewLayerName()" method="post" required>
<span class="close">×</span>
<p>Name your new Layer: </p>
<input placeholder="Type your desired layer name" type="text" name="newLayerName" id="newLayerName">
<button type="submit" value="submit" id="submitNewLayer" class="miro-btn miro-btn--primary miro-btn--small"
style="border: none; background-color: rgb(46,139,87); font-size: 15px; padding: 0px">Create</button>
</form>
</div>
</div>
<!----------------------------------------------------------------End of modal ------------------------------------------------------------------>
</div>
<template>
<div class="item item-layer"><span id="displayLayer"></span></div>
<span>sample layer 1</span>
<span>sample layer 2</span>
<!------------------------------------ template for the first function to add spans into ----------------->
</template>
<div class="miro-p-medium" style="font-size: 20px;">
<div class="item item-layer"><span id="displayLayer">sample layer 1</span></div>
<div class="item item-layer"><span>sample layer 2</span></div>
<div class="item item-layer"><span>sample layer 3</span></div>
<div class="item item-layer"><span>sample layer 4</span></div>
</div>
I have tried 2 ways to achieve this in my javascript code, 1 way with doing all of this inside a template and the other way to just use a div, at some point the input was being added when i appended it to body for about 1 second before disappearing, but I would also like the input from modal to inherit the same style and place in html as the 4 hardcoded spans I have right now
Javascript:
let template = document.querySelector('template').content
let layerTemplate = template.querySelector(".item-layer")
//modals
let modal = document.getElementById("myModal")
let btn = document.getElementById("btnCreate")
let span = document.getElementsByClassName("close")[0]
//function layerCreator(userInput) { // attempt with template
//let layerEl = layerTemplate.clondeNode(true)
//layerEl.querySelector("span").innerText = userInput
//document.getElementById("displayLayer").innerHTML = userInput
//return layerEl
//}
function layerCreatorX(input) { //attempt to directly insert into body
let x = document.createElement("span")
let t = document.createTextNode(input)
x.appendChild(t)
document.body.appendChild(x)
}
function validateNewLayerName() { // validates for empty input from input field
let input = document.forms["newLayerForm"]["newLayerName"].value
if (input == "" || input == null) {
alert("Cannot submit empty field, please try again!")
return false
}
else {
//this appends layer list with new layer
layerCreatorX(input)
}
}
I'm not too experienced in JS so I will be thankful for any suggestions or articles to look into
added just the most essential parts of the code, can add more if needed
Update: Forgot to include the function where i validate input from modal and use the function, it is now added in JS part
You are missing some key things:
You didn't post your validateNewLayerName function. This should return false, to avoid submitting the form.
You are not calling layerCreatorX and passing the value of newLayerName in the newLayerForm form.
You did not apply the class names item item-layer to the new span you created.
You are not adding the span to the .miro-p-medium container.
const template = document.querySelector('template').content
const layerTemplate = template.querySelector(".item-layer")
const modal = document.getElementById("myModal")
const btn = document.getElementById("btnCreate")
const span = document.getElementsByClassName("close")[0]
function validateNewLayerName() {
let input = document.forms["newLayerForm"]["newLayerName"].value
if (input == "" || input == null) {
alert("Cannot submit empty field, please try again!");
} else {
layerCreatorX(input);
}
return false; // Avoid submitting the form...
}
function layerCreatorX(input) {
const x = document.createElement("span");
const t = document.createTextNode(input);
x.className = 'item item-layer'; // Add the appropriate class.
x.appendChild(t);
document.querySelector('.miro-p-medium').appendChild(x);
// Let the modal window know that is can be closed now...
}
.item {
display: flex;
align-items: center;
height: 48px;
line-height: 48px;
cursor: pointer;
padding-left: 24px;
}
.item:hover {
background-color: rgba(0, 0, 0, 0.04);
}
.modal {
position: absolute;
border: thin solid grey;
background: #FFF;
padding: 0.5em;
right: 4em;
}
<div id="myModal" class="modal">
<div class="modal-content">
<form name="newLayerForm"
onsubmit="return validateNewLayerName()"
method="post" required>
<span class="close">×</span>
<p>Name your new Layer: </p>
<input type="text" id="newLayerName" name="newLayerName"
placeholder="Type your desired layer name">
<button type="submit" id="submitNewLayer" value="submit"
class="miro-btn miro-btn--primary miro-btn--small"
style="border: none; background-color: rgb(46,139,87); font-size: 15px; padding: 0px">Create</button>
</form>
</div>
</div>
<template>
<div class="item item-layer">
<span id="displayLayer"></span>
</div>
<span>sample layer 1</span>
<span>sample layer 2</span>
</template>
<div class="miro-p-medium" style="font-size: 20px;">
<div class="item item-layer"><span id="displayLayer">sample layer 1</span></div>
<div class="item item-layer"><span>sample layer 2</span></div>
<div class="item item-layer"><span>sample layer 3</span></div>
<div class="item item-layer"><span>sample layer 4</span></div>
</div>

Blur/unblur action on input clearance

I have the situation where I want to blur and unblur a background dynamically based on the inclusion of text in an input.
The unblur happens nicely, however, the re-blur on clearance of the input is not working? Not sure if I've just been staring at this too long, but hitting up SO because I'm slowly going insane looking at this. Thanks in advance for any help!
Code below:
<div>
<form name="search" class="searchBarClass" action="/action_page.php" style="margin:auto;max-width:300px">
<input type="text" placeholder="Search.." name="searchInput" onkeyup="unblur();blur();">
<button type="submit"><span class="material-icons">search</span></button>
</form>
</div>
<div id="background"></div>
Script for update:
function unblur() {
document.getElementById("background").style.filter = "none";
}
function blur() {
var x = document.forms["search"]["searchInput"].value;
if (x === "") {
document.getElementById("map").style.filter = "blur(2px)";
}
}
The intention is to blur the background whenever the input is empty. Here's some minimal code that accomplishes that:
const bgDiv = document.getElementById("background");
// blur background image when input is empty
function blurOnEmptyInput() {
var x = document.forms["search"]["searchInput"].value;
if (x === "") {
bgDiv.classList.add('blur');
} else {
bgDiv.classList.remove('blur');
}
}
/* style with CSS instead of embedding in JavaScript function */
.bg-image {
background-image: url("https://picsum.photos/300/100");
height: 100px;
width: 300px;
border: 1px solid gray;
}
.blur {
filter: blur(2px);
}
div {
margin: 1rem 0 0 1rem;
}
<div>
<form name="search">
<input placeholder="Search.." name="searchInput"
onkeyup="blurOnEmptyInput();">
</form>
</div>
<div id="background" class="bg-image blur"></div>

HTML JS form to div comments (temporary change)

I have seen many similar problems but when I try them they end up failing. It has gotten to the point where my code is totally messed up and I need some help both cleaning it up and fixing my issue. (using chrome)
So far I have tried selecting the value of the form and putting that into a div,
I have tried to use the button as just a link to start the script so that the page doesn't reset and also many other answers found on-line, none of them are helping so I am asking for a personalised help.
function on_comment_add() {
var main = document.getElementById("div1");
var add_user_name = document.createElement("div");
var add_user_comment = document.createElement("div");
add_user_name.setAttribute("id", "add_user_name");
add_user_comment.setAttribute("id", "add_user_comment");
<!-- var node = document.createTextNode("This is new."); -->
var node_1 = document.getElementById("user_name").value;
var node_2 = document.getElementById("user_comment").value;
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
var element = document.createElement("div");
element.setAttribute("id", "display_comment_div");
element.appendChild(add_user_name);
element.appendChild(add_user_comment);
main.appendChild(element);
main.innerHTML = element;
return false;
}
body {
background-color: lightGreen;
}
div.middle {
width: 80%;
margin-left: 10%;
background-color: #47e077;
height: 940px;
font-size: 10pt;
font-family: aubrey;
border: 3px solid gold;
}
.comments-form {
text-align: center;
}
#display_comment_div {
background: rgba(200, 54, 54, 0.1);
width: 80%;
margin-left: 9%;
border: 0.1px solid lightGreen;
border-radius: 25px;
}
#add_user_name {
width: 45%;
float: left;
}
#add_user_comment {
width: 45%;
display: inline-block;
float: right;
}
<div class="middle">
<div class="comments-form">
<form>
<label for="name" style="width:100px; display:inline-block;">Name</label>
<input id="user_name" type="text" placeholder="name goes here" style="width:300px; margin-left:5px;" />
<br><br>
<label for="comment" style="width:100px; display:inline-block;">Comment</label>
<textarea id="user_comment" placeholder="comment goes here" maxlength="150" style="width:300px;max-width:300px;"></textarea><br>
<button style="margin-left:310px;" onmousedown="return on_comment_add">Submit</button>
</form>
<div id="div1">
</div>
</div>
</div>
I guess what I am asking is if anyone can help me display the username and comment below the form but it seems tricky for me because I have gone through so many answers that don't work for me that I cannot think of any other ways to do it.
For clarification this code is not meant to keep the comments from the form nor is it meant to be a fully functioning site. I am just making slight modifications to some code so that I can hand it in as a college assignment.
Using onclick and pass the event inside:
<button style="margin-left:310px;" onclick="on_comment_add(event)">Submit</button>
And disable the default form submit action:
function on_comment_add(e) {
e.preventDefault()
var main = document.getElementById("div1");
var add_user_name = document.createElement("div");
var add_user_comment = document.createElement("div");
add_user_name.setAttribute("id", "add_user_name");
add_user_comment.setAttribute("id", "add_user_comment");
var node_1 = document.createElement("div");
node_1.innerHTML= document.getElementById("user_name").value;
var node_2 = document.createElement("div");
node_2.innerHTML = document.getElementById("user_comment").value;
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
var element = document.createElement("div");
element.setAttribute("id", "display_comment_div");
element.appendChild(add_user_name);
element.appendChild(add_user_comment);
main.appendChild(element);
return false;
}
Workable example: https://jsfiddle.net/kingychiu/z6gnqswn/
Change type to "button" to prevent automatical form sending and add parentheses to onmousedown expression:
<button type="button" style="margin-left:310px;" onmousedown="return on_comment_add()">Submit</button>
Then change this
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
to this (since node_1, node_2 are values, not elements):
add_user_name.innerHTML = node_1;
add_user_comment.innerHTML = node_2;
And remove that line
main.innerHTML = element;
above
return false;
That should work.

Categories