How Can I Make My JS Search Bar Be NOT Case Sensitive? - javascript

So I have created a web-site to which you can upload, download, delete and preview files. I also have a java-script function that lets the user search through the files. Only thing is, that the search is case sensitive. Can anyone help me with a sample code on how should I change my script so that it will NOT be case sensitive anymore? I am very new to ASP.NET and still trying to wrap my head around.
Here is the Index page:
#model IEnumerable<Proiect2PracticaClona.Models.Files>
<center>
<h1>Daca nici acu nu merge ... ma sinucid</h1>
<h2>Sa moara mama</h2>
<hr />
#if (User.IsInRole("Admin"))
{
<form methord="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<input type="file" name="fifile" />
#Html.RadioButton("category", "incepator")
#Html.RadioButton("category", "intermediar")
#Html.RadioButton("category", "admin")
<input type="submit" value="Upload" />
<hr />
</form>}
<div>
File Name:<input id="search" onkeyup="search()" placeholder="cauta"/>
</div>
<table class="table">
#if (User.IsInRole("User"))
{
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</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 active">
<a class="nav-link">Incepatori <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link">Avansati</a>
</li>
<li class="nav-item dropdown">
</li>
<li class="nav-item">
<a class="nav-link disabled">Admini</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
}
<tr>
<th>File Name</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.info</td>
<td>Download</td>
#if (User.IsInRole("Admin"))
{
<td>Delete</td>
}
<td>Viewer</td>
</tr>
}
</table>
#section scripts
{
<script>
function search() {
$("tr").each(function (index, value) {
if (index > 0 && !$(this).find("td")[0].innerText.includes($("#search").val())) {
$(this).attr("hidden", true);
} else {
$(this).removeAttr("hidden");
}
console.log(value);
})
}
</script>
}
</center>

Why not convert both sides to lowercase when checking. This case it does not matter what the casing of element in td block is and what is the case of text inserted by user.
We use this a lot in out application to make comparisons.
function search() {
$("tr").each(function (index, value) {
if (index > 0 && !$(this).find("td")[0].innerText.toLowerCase().includes($("#search").val().toLowerCase())) {
$(this).attr("hidden", true);
} else {
$(this).removeAttr("hidden");
}
console.log(value);
})
}

Case sensitivity can be negated by transforming the value on either side of the query to lowercase or to uppercase (according to your preference.
So your search logic needs to change from
if (index > 0 && !$(this).find("td")[0].innerText.includes($("#search").val())) {
To this:
if (index > 0 && !$(this).find("td")[0].innerText.toLowerCase().includes($("search").val().toLowerCase())) {

Related

Selenium how to get the elements who doesn't have a name or id

i want to find the two inputs using selenium using findElement by css
i want to fill in the two inputs, i was only able to find one input with "input[type='text']" and im not sure how to get the other one
please check my html
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/tasks">Todo List</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"><a class="nav-link" href="/">Home</a></li>
<li class="nav-item"><a class="nav-link" href="/tasks">Tâches</a></li>
<li class="nav-item"><a class="nav-link" href="/">Déconnexion</a></li>
</ul>
</div>
</nav>
<div class="container mt-5"></div>
</div>
<div>
<h2>Liste des tâches</h2>
<div class="alert alert-info">Aucune tâche n'a encore été créée.</div>
<hr />
<h2>Créer une nouvelle tâche</h2>
<div class="row">
<div class="col">
<label>Nom de la tâche</label
><input type="text" class="form-control" value="" />
</div>
<div class="col">
<label>Description de la tâche en une ligne</label
><input type="text" class="form-control" value="" />
</div>
<div class="col">
<br /><button class="btn btn-primary">Ajouter la tâche</button>
</div>
</div>
</div>
You can either use XPath, and to find it easily open Inspect Element, right click on input, click on Copy XPath,or you can get all matching elements and select it from the list, like
findElements("input[type='text']")[0]
findElements("input[type='text']")[1]
By xpath, for example in Firefox
Right click on page -> Select (Inspect Element), pick an element from the page, then right click on highlighted html -> Copy -> Xpath
Check
https://www.lambdatest.com/blog/complete-guide-for-using-xpath-in-selenium-with-examples/
If you found the first input element, you can simply do the same you did to find it but use find_elements() instead of find_element().
It will return a list with the two inputs.

Adding onclick function in anchor tag which is not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am have made dropdown using bootstarap. I have added onlcick funtions in my anchor tags in dropdown. I just want make my text box readonly if one of the link is clicked on. I have used js to make text boxes read only. Please Help me to solve my problem. Below is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
<title>Mole Calculator | Chemistry Calculator</title>
</head>
<body>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
<div class="container-fluid">
<a class="navbar-brand" href="#"><h4>
<b>Chemistry Calculator</b>
</h4></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 text-uppercase">
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
</ul>
</div>
</div>
</nav>
<div class="container" style="padding-top: 5%;">
<div class="card px-4 py-5" style="width: 650px;">
<div class="card-block">
<form action="/Chemistry-Calculator/Number-Of-Moles">
<div class="mb-3">
<label for="givenMass" class="form-label">Given Mass of
Substance</label> <input type="text" class="form-control" id="givenMass"
aria-describedby="emailHelp" name="givenMass"
value="${givenMass}" style="width: 600px">
</div>
<div class="mb-3">
<label for="molarMass" class="form-label">Molar Mass</label> <input
type="text" class="form-control" id="molarMass" name="molarMass"
value="${molarMass}" style="width: 600px">
</div>
<div class="mb-3">
<label for="molarMass" class="form-label">Moles</label> <input
type="text" class="form-control"
id="molarMass" name="moles" value="${moles}" style="width: 600px">
</div>
<input class="btn btn-outline-success" type="submit"
value="Calculate">
<div class="btn-group">
<button type="button" class="btn btn-success dropdown-toggle"
data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" onclick="readonlyForMoles()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
<li><a class="dropdown-item" onclick="readonlyForMolarMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
<li><a class="dropdown-item" onclick="readonlyForGivenMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
</ul>
</div>
</form>
</div>
</div>
</div>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script type="text/javascript" src="../javascript/script.js"></script>
</body>
</html>
My Java Script File:
function readonlyForGivenMass() {
var x = document.getElementById("givenMass").readOnly;
}
function readonlyForMolarMass() {
var x = document.getElementById("molarMass").readOnly;
}
function readonlyForMoles() {
var x = document.getElementById("moles").readOnly;
}
Actually this is small part of java project. Hence I have used jsp and jstl.
My file structure:
you are just assigning but declaring it, just need to make it true, so given id would be readonly, please find below snippets
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
<title>Mole Calculator | Chemistry Calculator</title>
</head>
<body>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
<div class="container-fluid">
<a class="navbar-brand" href="#"><h4>
<b>Chemistry Calculator</b>
</h4></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 text-uppercase">
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
</ul>
</div>
</div>
</nav>
<div class="container" style="padding-top: 5%;">
<div class="card px-4 py-5" style="width: 650px;">
<div class="card-block">
<form action="/Chemistry-Calculator/Number-Of-Moles">
<div class="mb-3">
<label for="givenMass" class="form-label">Given Mass of
Substance</label> <input type="text" class="form-control" id="givenMass"
aria-describedby="emailHelp" name="givenMass"
value="${givenMass}" style="width: 600px">
</div>
<div class="mb-3">
<label for="molarMass" class="form-label">Molar Mass</label> <input
type="text" class="form-control" id="molarMass" name="molarMass"
value="${molarMass}" style="width: 600px">
</div>
<div class="mb-3">
<label for="moles" class="form-label">Moles</label> <input type="text" class="form-control" id="moles" name="moles" value="${moles}" style="width: 600px">
</div>
<input class="btn btn-outline-success" type="submit"
value="Calculate">
<div class="btn-group">
<button type="button" class="btn btn-success dropdown-toggle"
data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" onclick="readonlyForMoles()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
<li><a class="dropdown-item" onclick="readonlyForMolarMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
<li><a class="dropdown-item" onclick="readonlyForGivenMass()" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
</ul>
</div>
</form>
</div>
</div>
</div>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script type="text/javascript" src="../javascript/script.js"></script>
<script>
function readonlyForGivenMass() {
document.getElementById("givenMass").readOnly = true;
document.getElementById("molarMass").readOnly = false;
document.getElementById("moles").readOnly = false;
}
function readonlyForMolarMass() {
document.getElementById("givenMass").readOnly = false;
document.getElementById("molarMass").readOnly = true;
document.getElementById("moles").readOnly = false;
}
function readonlyForMoles() {
document.getElementById("givenMass").readOnly = false;
document.getElementById("molarMass").readOnly = false;
document.getElementById("moles").readOnly = true;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
<title>Mole Calculator | Chemistry Calculator</title>
</head>
<body>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">
<div class="container-fluid">
<a class="navbar-brand" href="#"><h4>
<b>Chemistry Calculator</b>
</h4></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 text-uppercase">
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="/Chemistry-Calculator/">Home</a></li>
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="/Chemistry-Calculator/about">About</a></li>
</ul>
</div>
</div>
</nav>
<div class="container" style="padding-top: 5%;">
<div class="card px-4 py-5" style="width: 650px;">
<div class="card-block">
<form action="/Chemistry-Calculator/Number-Of-Moles">
<div class="mb-3">
<label for="givenMass" class="form-label">Given Mass of
Substance</label> <input type="text" class="form-control" id="givenMass"
aria-describedby="emailHelp" name="givenMass"
value="${givenMass}" style="width: 600px">
</div>
<div class="mb-3">
<label for="molarMass" class="form-label">Molar Mass</label> <input
type="text" class="form-control" id="moles" name="molarMass"
value="${molarMass}" style="width: 600px">
</div>
<div class="mb-3">
<label for="molarMass" class="form-label">Moles</label> <input
type="text" class="form-control"
id="molarMass" name="moles" value="${moles}" style="width: 600px">
</div>
<input class="btn btn-outline-success" type="submit"
value="Calculate">
<div class="btn-group">
<button type="button" class="btn btn-success dropdown-toggle"
data-bs-toggle="dropdown" aria-expanded="false">Choose what to calculate </button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" onclick="readonlyForMoles(event)" href="/Chemistry-Calculator/Mole-Calculator">Calculate Moles</a></li>
<li><a class="dropdown-item" onclick="readonlyForMolarMass(event)" href="/Chemistry-Calculator/Mole-Calculator">Calculate Molar Mass</a></li>
<li><a class="dropdown-item" onclick="readonlyForGivenMass(event)" href="/Chemistry-Calculator/Mole-Calculator">Calculate Given mass</a></li>
</ul>
</div>
</form>
</div>
</div>
</div>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function readonlyForGivenMass(event) {
event.preventDefault()
var x = document.getElementById("moles").readOnly= false;
var x = document.getElementById("givenMass").readOnly= true;
var x = document.getElementById("molarMass").readOnly= false;
}
function readonlyForMolarMass(event) {
event.preventDefault()
var x = document.getElementById("molarMass").readOnly = true;
var x = document.getElementById("moles").readOnly= false;
var x = document.getElementById("givenMass").readOnly= false;
}
function readonlyForMoles(event) {
event.preventDefault()
var x = document.getElementById("molarMass").readOnly = false;
var x = document.getElementById("moles").readOnly = true;
var x = document.getElementById("givenMass").readOnly= false;
}
</script>
</body>
</html>
if you want means you can remove event.preventDefault in each function and
I hope this code will works for you. Thank you

How can I create dynamic menu with submenu in vue 2?

I have a problem and if you can help me I would be grateful, because I am working with vue for 3 weeks.
I try to create a menu with submenu in vue 2 by two weeks and I can't succeed. the menu is created , but when I go to submenu is won't create it. the code is next:
<script>
import image from "./assets/img/logo-just-escape.png"
import axios from "axios"
export default {
data(){
const lang = localStorage.getItem('lang')
return {
imagel: image,
lang: lang,
languages:null,
menu:null,
submenu:null
}
},
async created(){
try {
var res =await axios.get(`lng`);
this.languages=res.data;
const valmenu="titles/value?language="+this.lang;
res=await axios.get(valmenu);
this.menu=res.data;
this.submenu=this.getSubMnu(this.menu);
console.log(this.submenu)
}catch(e){
console.error(e);
}
},
methods: {
handleChange(event){
localStorage.setItem('lang',event.target.value);
window.location.reload();
},
getSubMnu(value){
let temp='';
let sbmenu=[];
let variable=null;
for(temp in value){
if('2'==value[temp].subtitle){
variable=value[temp];
let temp1=value[temp].link+"\/"+this.menu[temp].id;
variable.link=temp1;
sbmenu.push(variable);
}
}
return sbmenu;
}
}
}
</script>
<template>
<div id="app" class="bg-dark">
<div>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="/">
<img width="100" height="50" :src="imagel"/>
</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<div v-for="menuButton in this.menu" :value="menuButton.title" :key="menuButton.id">
<li class="nav-item" v-if="menuButton.subtitle ===0">
<router-link :to="menuButton.link" ><span class="nav-link">{{menuButton.title}}</span></router-link>
</li>
<li class="nav-item dropdown" v-if="menuButton.subtitle ===1" style="color: white;">
<span class="nav-link dropdown-toggle" data-toggle="dropdown" aria-expanded="false">{{menuButton.title}}</span>
<div v-for="tempor in this.submenu" class="dropdown-menu dropdown-menu-right bg-dark" :value="tempor.title" :key="tempor.id">
<span class="nav-link">{{tempor.title}}</span>
<router-link :to="tempor.link" #click.name><span class="nav-link">{{tempor.title}}</span></router-link>
</div>
</li>
</div>
<li class="nav-item">
<select class="selectpicker form-control" v-model="lang" data-width="fit" #change="handleChange($event)">
<option v-for="langu in languages" :value="langu.language_short" :key="langu.id">
{{langu.language}}
</option>
</select>
</li>
</ul>
</div>
</nav>
<div class="divmargin" >
<router-view/>
</div>
</div>
</div>
</template>
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'submenu' of undefined"
found in
---> at src/App.vue
If someone can give me some answer to this I will be very grateful.
Thank you,
Vlad.

Angular 8 loose data after refresh page

I have isAdmin boolean property which I am checking user logged in as user or admin.
Backend is .net core 2.2, db - Postgre.
Everything works fine but after refresh I lose isAdmin value.
I have conditional show hide dropdown which is available only for admin roles.
How don't lose data after refreshing?
P.S. How to add logic also to my guard for isAdmin property?
My component looks like:
model: any = {};
constructor(public authService: AuthService, private alertify: AlertifyService, private router:
Router) { }
ngOnInit() {
}
login() {
this.authService.login(this.model).subscribe(next => {
this.model.isAdmin = true;
this.alertify.success('Logged in as Admin')
}, error => {
this.alertify.error(error)
}, () => {
this.router.navigate(['/projects'])
})
}
loginAsUser() {
this.authService.loginAsUser(this.model).subscribe(next => {
this.model.isAdmin = false;
this.alertify.success('Logged in as User')
}, error => {
this.alertify.error(error)
}, () => {
this.router.navigate(['/home'])
})
}
loggedIn() {
return this.authService.loggedIn();
}
logout() {
localStorage.removeItem('token');
this.alertify.message('logged out');
this.router.navigate(['/home'])
}
My html looks like:
<nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">
<div class="container">
<a class="navbar-brand" [routerLink]="['/home']">
<img [src]="iteraLogo" alt="Itera">
</a>
<div *ngIf="loggedIn()" class="dropdown" dropdown [hidden]="!model.isAdmin">
<a class="dropdown-toggle" dropdownToggle>
<strong class="text-primary">Admin Panel</strong>
</a>
<div class="dropdown-menu mt-4" *dropdownMenu>
<ul class="navbar-nav">
<li class="nav-item" routerLinkActive="router-link-active">
<a class="nav-link" [routerLink]="['/projects']">Projects</a>
</li>
<li class="nav-item" routerLinkActive="router-link-active">
<a class="nav-link" [routerLink]="['/hypervisors']">Hypervisors</a>
</li>
<li class="nav-item" routerLinkActive="router-link-active">
<a class="nav-link" [routerLink]="['/management']">Management</a>
</li>
<li class="nav-item" routerLinkActive="router-link-active">
<a class="nav-link" [routerLink]="['/users']">Users</a>
</li>
<li class="nav-item" routerLinkActive="router-link-active">
<a class="nav-link" [routerLink]="['/user-projects']">Users Projects</a>
</li>
</ul>
</div>
</div>
<ul class="navbar-nav mr-auto">
<li class="nav-item" routerLinkActive="router-link-active">
<a class="nav-link" [routerLink]="['/test']">About</a>
</li>
</ul>
<div *ngIf="loggedIn()" class="dropdown" dropdown>
<a class="dropdown-toggle" dropdownToggle>
Welcome <strong>{{ authService.decodedToken?.unique_name | titlecase }}</strong>
</a>
<div class="dropdown-menu mt-3" *dropdownMenu>
<a class="dropdown-item text-primary" [routerLink]="['/projects/',
authService.decodedToken?.nameid ]"><i class="fa fa-archive"> My Projects</i></a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger" (click)="logout()"><i class="fa fa-sign-
out"> Logout</i></a>
</div>
</div>
<form *ngIf="!loggedIn()" #loginForm="ngForm" class="form-inline my-2 my-lg-0">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fa fa-user-circle-o text-primary" aria-hidden="true"></i>
</div>
</div>
<input class="form-control" placeholder="Username" name="username" required
[(ngModel)]="model.username" />
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fa fa-unlock text-danger" aria-hidden="true"></i>
</div>
</div>
<input class="form-control" placeholder="Password" name="password" required type="password"
[(ngModel)]="model.password" />
</div>
<div>
<button [disabled]="!loginForm.valid" type="submit" (click)="loginAsUser()" class="btn btn-primary my-2 my-sm-0">
<i class="fa fa-user-circle" aria-hidden="true"></i> User
</button>
<button [disabled]="!loginForm.valid" type="submit" (click)="login()" class="btn btn-success
my-2 my-sm-0">
<i class="fa fa-user-secret" aria-hidden="true"></i> Admin
</button>
</div>
</form>
</div>
</nav>
My guard looks like:
canActivate(): boolean {
if(this.authService.loggedIn()) {
return true
}
this.alertify.error('You have no access to see this page!!!');
this.router.navigate(['/home']);
return false;
}
When you refresh the page it does not persist variable values, you need to store either in local storage or cookie.
A simple way to solve this is to use this lib:
https://www.npmjs.com/package/ng2-cookies
To install this library, run:
npm install ng2-cookies
Component
import { Cookie } from 'ng2-cookies/ng2-cookies';
ngOnInit() {
this.model.isAdmin = Cookie.get('isAdmin');
}
login() {
this.authService.login(this.model).subscribe(next => {
Cookie.set('isAdmin', 'true');
this.alertify.success('Logged in as Admin')
}, error => {
this.alertify.error(error)
}, () => {
this.router.navigate(['/projects'])
})
}
you can use ngx-cookie-service also
https://www.npmjs.com/package/ngx-cookie-service
You will have to store your Auth_Token in localhost/indexDB/SessionStorage and then inside your route guard check if that token is valid or not.
This way your app will not require authentication until your token is valid.
Use this npm module to achieve this : enter link description here
You have to make the auth service API call with ngoninit of the components and get the isAdmin flag. That way when u refresh everytime ngOnInit will get involved and u ll get that flag.
ngOnInit(){ this.authService.login(this.model).subscribe(next => {
this.model.isAdmin = true;
});
}
Set a variable in localStorage upon successful login, like
isloggedIn(authUser) {
return this.httpClient.post<any>(`${this.apiUrl}/api/users/login`, {user: authUser})
.do(res => this.setSession(res.user))
.shareReplay();
}
private setSession = (authResult) => {
localStorage.setItem('TOKEN', authResult.token);
localStorage.setItem('loggedUser', 'y');
this._router.navigate(['dashboard'])
};
Next time when you enter any component, check
if(!localStorage.getItem('loggedUser')){
this._router.navigate(['login']);
return false;
}
return true;
this will authenticate user without calling API again. just get key from LocalStorage.

Bootstrap Navbar Search Form Input has Error Class not being Applied

So I'm able to control the form the way I want to with javascript (at least form submission functionality wise), and a active working form is here on this code pen. However when the form is "invalid" i'm having trouble applying the bootstrap input class "has-error" to this form and turning the color around the input red. More can be found out about the "has-error" class here: http://getbootstrap.com/css/#forms-control-validation
https://codepen.io/MaineCannabisKid/pen/ZymzJO
Here is the Form code
<form class="navbar-form navbar-nav search-form" method="get" action="search.php" name="searchForm" id="searchForm">
<!-- hidden type input -->
<input type="hidden" name="searchType" id="searchType" value="users" required>
<div class="input-group">
<input type="text" id="searchInput" name="searchInput" class="form-control" aria-label="Search the site" placeholder="Search Users">
<div class="input-group-btn">
<button type="button" class="btn btn-default" id="searchFormSubmit">Search</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu">
<li>Users</li>
<li>Another Search</li>
</ul>
</div>
</div>
</form>
and here's the javascript
console.log("Navbar.js Connected");
// Search Form Validate Function
function searchFormValidate() {
// Check is Search Input value is null, if so return false (Validation didn't pass)
return $('#searchInput').val() == "" ? false : true;
}
// When Search Users is clicked on
$('#searchForm-users').on('click', function() {
$('#searchType').val('users');
$('#searchInput').attr("placeholder", "Search Users");
});
// When Another Search is clicked on
$('#searchForm-another').on('click', function() {
$('#searchType').val('another');
$('#searchInput').attr("placeholder", "Search Something Else");
});
// When Search is clicked Submit Form
$("#searchFormSubmit").on('click', function() {
if(searchFormValidate()) {
document.searchForm.submit();
} else {
// Right here is where the form should apply the has-error class
console.log("Validation Error");
}
});
This will fix your issue.
$("#searchInput").parent().addClass("has-error");
Note: the line around the input shows in red but due to your background colors, It won't visible to the eye.
console.log("Navbar.js Connected");
// Search Form Validate Function
function searchFormValidate() {
// Check is Search Input value is null, if so return false (Validation didn't pass)
return $('#searchInput').val() == "" ? false : true;
}
// When Search Users is clicked on
$('#searchForm-users').on('click', function() {
$('#searchType').val('users');
$('#searchInput').attr("placeholder", "Search Users");
});
// When Another Search is clicked on
$('#searchForm-another').on('click', function() {
$('#searchType').val('another');
$('#searchInput').attr("placeholder", "Search Something Else");
});
// When Search is clicked Submit Form
$("#searchFormSubmit").on('click', function() {
if (searchFormValidate()) {
// form valid submit form
document.searchForm.submit();
} else {
// form isn't valid, turn has-error on
console.log("Validation Error");
$("#searchInput").parent().addClass("has-error");
}
});
/* Navbar */
.navbar-default {
margin: 0 auto;
border-radius: 0;
z-index: 100;
background-color: transparent!important;
border-color: transparent!important;
}
/* Navbar Search Form */
.search-form .btn-default {
background: #ac3911;
border-color: rgba(149, 48, 15, 1);
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: transparent!important;
}
/* Drop Down Button */
.search-form .btn-default.dropdown-toggle {
border-left: 1px solid rgba(149, 48, 15, 1);
}
/* End Navbar Search*/
<link href="https://bootswatch.com/united/bootstrap.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-nav-demo" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
真 Makoto
</div>
<div class="collapse navbar-collapse" id="bs-nav-demo">
<ul class="nav navbar-nav navbar-right">
<form class="navbar-form navbar-nav search-form" method="get" action="#" name="searchForm" id="searchForm">
<!-- hidden type input -->
<input type="hidden" name="searchType" id="searchType" value="users" required>
<div class="input-group">
<input type="text" id="searchInput" name="searchInput" class="form-control" aria-label="Search the site" placeholder="Search Users">
<div class="input-group-btn">
<button type="button" class="btn btn-default" id="searchFormSubmit">Search</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu">
<li>Users</li>
<li>Another Search</li>
</ul>
</div>
</div>
</form>
</ul>
</div>
</div>
</nav>

Categories