duplicate entry in localstorage - Javascript - javascript

I'm attempting to build a simple address book app using a more OOP approach.
Currently it adds to localStorage without problem; but the next task I wanted to accomplish was a function that displays the Key => value pairs within the HTML. I'm stuck at the first hurdle.
When I call the displayContacts() function on the click event, it is creating another empty object within the LocalStorage. Every time I reload the page and click the 'find' button (and assuming no additional information has been added to the form), a new entry will be added to localStorage such as:
{"first_name":"","last_name":"","email":"","telephone":""}
Thanks in advance
< !-- begin snippet: js hide: false console: true babel: false -->
var addressBook = {
people : JSON.parse(localStorage.getItem('contacts')) || [],
cacheDom : function(){
this.$parent = $('.address_book');
this.$display = $('.find_contacts');
},
bindEvent : function(){
this.$parent.on('submit', this.getFormData.bind(this));
this.$display.on('click', this.displayContacts.bind(this));
},
getStorage : function(param){
return localStorage.getItem();
},
setStorage : function(){
var storage = localStorage.getItem("contacts");
localStorage.setItem("contacts", JSON.stringify(this.people));
},
displayContacts : function(){
var contacts = this.people;
console.log(contacts);
},
getFormData : function(e){
var contacts = {};
var target = e.target.length;
for(var i = 0; i < target; i++){
if(e.target[i].nodeName === "INPUT"){
contacts[e.target[i].name] = e.target[i].value;
/*console.log(contacts);*/
}
}
this.people.push(contacts);
this.setStorage();
return false;
},
render: function(){
},
init : function(){
this.cacheDom();
this.bindEvent();
this.setStorage();
}
}
addressBook.init();
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="./bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
<link href="./bootstrap-3.3.7-dist/css/custom.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row wrapper">
<div class="col-md-4 input_field">
<form class="address_book" method="post">
<div class="form-group">
<label for="exampleInputEmail1">First Name</label>
<input type="text" class="form-control first_name" id="exampleInputEmail1" placeholder="First Name" name="first_name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Last Name" name="last_name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Telephone</label>
<input type="number" class="form-control" id="exampleInputPassword1" placeholder="Phone Number" name="telephone">
</div>
<button type="submit" class="btn btn-default submit_to_storage">Submit</button>
<button type="edit" class="btn btn-default submit_to_storage">edit</button>
<button type="delete" class="btn btn-default submit_to_storage">delete</button>
<button type="find" class="btn btn-default find_contacts">find</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-push-10 output">
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="./bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<script src="./bootstrap-3.3.7-dist/js/localStorage.class.js"></script>
</body>
</html>

Your button is of type find
<button type="find" class="btn btn-default find_contacts">
This is not a valid type, and instead the button goes back to the default type, which is submit.
A submit button inside a form, submits the form, so not only are you calling the click handler on the button, but the submit handler for the form as well, which inserts into localStorage.
This is why, when you click the button it inserts in to localStorage.
To fix the issue, add a type of button to all the buttons that aren't supposed to submit the form.
<button type="submit" class="btn btn-default submit_to_storage">Submit</button>
<button type="edit" class="btn btn-default submit_to_storage">edit</button>
<button type="delete" class="btn btn-default submit_to_storage">delete</button>
<button type="find" class="btn btn-default find_contacts">find</button>
The only valid types for a button are
submit
reset
button

Related

Show Pop up message after form validation in javascript

I am new in javascript and currently I am creating an enrolment form where it will validate the cellphone where it only accepts 11 characters and numbers. the only problem is that everytime I click on submit, instead of the message popping up, it completely refreshes my tab. Is there any way to fix this?
Form Code:
<!doctype html>
<html lang="en">
<head>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="Homepage.html"><img src="USTLogo.png" width="30" height="30" alt="">School</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="Homepage.html">HOME<span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
<title>Enrollment Form</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- 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">
<!-- CSS -->
<link href = "design.css" rel = "stylesheet" type="text/css"/>
<script src="JAVASCRIPT.js" type="text/jsx"></script>
</head>
<body>
<h1 class="display-1">Enrollment Form</h1>
<div class="container">
<div class="row">
<!-- empty space on the left side -->
<div class="col-lg-3"></div>
<!-- Main Content -->
<div class="col-lg-6">
<div id ="ui">
<form id = "form" class="form-group">
<div class="row">
<div class="col-lg-8">
<label >Cellphone Number</label>
<input id = "Cp_Number" type="text" class="form-control" placeholder="Enter Cellphone Number..." required>
</div>
<div class="col-lg-4">
<label >Age</label>
<input id = "Age" type="text" class="form-control" placeholder="Enter your age..." required>
</div>
<br>
<div class="row">
<div class="col-lg-6">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
<div class="col-lg-6">
Cancel
</div>
</div >
</form>
</div>
</div>
<!-- empty space on the right side -->
<div class="col-lg-3"></div>
</div>
</div>
<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>
</body>
</html>
Note: I will be removing most of the content in the form and will only include the fields where it needs validation
JS code:
const Cp_num = documet.getElementById('Cp_Number')
const age = document.getElementById('Age')
const form = document.getElementById('form')
form.addEventListener('submit', (e) =>{
var isValid = true;
e.preventDefault();
if(isNaN(Cp_num) || Cp_num.value == null || Cp_num.value == ''){
alert ("Your Cellphone number is invalid!")
isValid == false;
}
if (Cp_num >=12){
alert ("Your Cellphone number is invalid!")
isValid == false;
}
if(isNaN(age) || age.value == null || age.value == ''){
alert ("Your Age is invalid!")
isValid == false;
}
if (isValid == true){
popUp();
}
})
Stop using your custom javascript in the head tag. Because, of this the scripts loads before the contents and doesn't find the form element in the DOM before initialization. So, use any custom javascript inside the body tag and below all the html elements. But remember to include any other dependencies before your custom scripts. Hope it solves the problem.
What's happening here is that your script tag is in your head:
<script src="JAVASCRIPT.js" type="text/jsx"></script>
And for that reason, your HTML hasn't been loaded completely, so a "form" element with the id of "form" does not exist, thus, you get an error (check your console in your browser).
This is why your e.preventDefault() method doesn't work. Because again, your HTML hasn't been loaded yet.
You have two options:
Put the script tag at the bottom of your body:
Very self-explanatory, put the script tag at the end of your body, so your whole HTML loads first, and then your JavaScript file.
Use the "defer" attribute in your script tag:
I won't explain what the defer does in depth here, but if you want some quick answer, it basically waits for your HTML to fully load before using any of the JavaScript code.
So you can try this:
<script src="JAVASCRIPT.js" type="text/jsx" defer></script>
(By the way, this method does not require you to move the script tag out of your HTML head)
You can learn more about defer here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer
(EDIT): By further inspection of the code, I found that you were using the "type" parameter in your script tag. You don't need this, and this is causing you the problem of your script tag not being used:
So from:
<script src="JAVASCRIPT.js" type="text/jsx"></script>
do:
<script src="JAVASCRIPT.js" defer></script>
(Another gotcha) You have a typo on the first "document" that you were selecting:
const Cp_num = documet.getElementById('Cp_Number')
"documet" is not defined, you have to change it to:
const Cp_num = document.getElementById('Cp_Number')

access table from PHP database in Javascript

I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.

Jquery radio button starts endless loop?

I want to get an answer from the php file if I click on one of the radio buttons, but if I use the radio button, the alert appers in an endless loop. Why? And how do I get the alert only once?
I try it with only a „normal“ button, then it works:
If I click on the button, the ajax responds the values in the alert once.
Thank you
<!doctype html>
<html lang="de">
<head>
<title>test</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div class="container">
<br>
<br>
<button type="button" class="btn btn-dark" id="go">Go</button>
<div class="row">
<div class="btn-group" id="auswahl" data-toggle="buttons">
<label class="btn btn-outline-primary active">
<input type="radio" name="aktionswahl" value="alles" checked autocomplete="off"> Alles
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="aktionswahl" value="blue" autocomplete="off"> blue
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="aktionswahl" value="red" autocomplete="off"> red
</label>
</div>
</div>
</div><!--Container-->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">></script>
<script>
$(function() {
$("input[name=aktionswahl]").focus(function () {
//var auswahl = this.value;
var sqlwhere = "where aktion=4 and Datum >= '2017-12-05' and Datum < '2017-12-07'";
ask(sqlwhere);
});
});
$(function() {
$("#go").click(function () {
var sqlwhere = "where aktion=4 and Datum >= '2017-12-05' and Datum < '2017-12-07'";
ask(sqlwhere);
});
});
function ask(sqlwhere) {
$.ajax({
type: 'POST',
url: 'read_sql.php',
data: { sqlwhere:sqlwhere }
}).done(function(data) { alert(data); });
return false;
}
</script>
</body>
</html>
As the alert appears, the radio button will lose focus. As you close the alert, the focus will return which triggers the alert which causes the radio button to lose focus but when you close that alert ...
Use console.log instead
Try this, your code is right just need one change...
write return false; immediately after alert.
means...function(data) { alert(data); return false; }

Can't get JS function working properly

I've got this form with bootstrap but I can't find why it's not working properly ant I've no idea why.
HEAD>>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css"/>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/corrections.css" rel="stylesheet" type="text/css"/>
<script src="js/JQuery-2.1.1-min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
--> code here
</body>
HTML >>
<div class="col-lg-4">
<form class="form-inline well">
<div class="form-group">
<label class="sr-only" for="text">Some label</label>
<input id="text" type="text" class="form-control" placeholder="Text here">
</div>
<button type="submit" class="btn btn-primary pull-right">Ok</button>
<div class="alert alert-danger" style="display:none">
<h4>Error</h4>
Required amount of letters is 4
</div>
<div class="success alert-success" style="display:none">
<h4>Success</h4>
You have the required amount of letters
</div>
</form>
</div>
JS >>
<script>
$(function () {
$("form").on("submit", function () {
if ($("input").val().length < 4) {
$("div.form-group").addClass("has-error");
$("div.alert").show("slow").delay(4000).hide("slow");
return;
} else if ($("input").val().length > 3) {
$("div.form-group").addClass("has-success");
$("div.success").show("slow").delay(4000).hide("slow");
return;
}
});
});
</script>
the alert class shows everytime, any idea why?
The use of $("input") here is unusual. That selector will pull back all elements on the page that are <input>s, which is almost certainly not what you mean. (If there are other inputs on the page, you might get exactly what you're describing.) Use a more precise selector, like $("#text"), and maybe use debug to output the value of val().length so you know what you're evaluating.
(On a side note, "text" is not a very useful name for a text input, and your else-if seems redundant, but they probably aren't causing problems in your code.)

Save dynamically created buttons

Below is my code. In this by clicking on Add Group, a button is dynamically created and added in fooBar. But when I refresh the page it goes away. I want to create the buttons and save it in the fooBar.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Content</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="stylesheets/bootstrap.min.css" rel="stylesheet">
<link href="stylesheets/bootstrap.css" rel="stylesheet">
<link href="stylesheets/bootstrap-theme.min.css" rel="stylesheet">
<link href="stylesheets/bootstrap-theme.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<SCRIPT language="javascript">
window.onload = function() {
document.getElementById('btnAdd').onclick = function()
{
myFunction();
};
var person;
var element;
function myFunction()
{
var x;
person = prompt("Please enter Group Name");
if (person != null)
{
add(element);
// x = "Hello " + person + "! How are you today?";
// document.getElementById("demo").innerHTML = x;
}
}
function add(type) {
//Create an input type dynamically.
element = document.createElement("button");
var t = document.createTextNode(person);
element.appendChild(t);
//Assign different attributes to the element.
// element.type = type;
// element.value = type; // Really? You want the default value to be the type string?
// element.name = type; // And the name too?
element.className = "btn btn-default";
span.innerHTML=person;
element.onclick = function() { // Note this is a function
//alert("Do it again!");
$("#btn-group").load("head.html");
};
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
// var d = document.getElementById('fooBar');
// d.appendChild(i);
}
};
// function copy()
// {
// var n1 = document.getElementById('addKeyword');
// var n2 = document.getElementById('getKeyword');
// n2.innerText = n1.value;
// }
</SCRIPT>
<script>
$(function(){
$("#btn-group").load("head.html");
});
</script>
</head>
<body>
<div class="btn-group" id="fooBar">
<!-- <button type="button" class="btn btn-default">Marketing</button>
<button type="button" class="btn btn-default">Internet</button>
<button type="button" class="btn btn-default">Politics</button>-->
<button type="button" class="btn btn-default" id="btnAdd">Add Group</button>
</div>
<div class="boxed">
<h4>Group:<span class="label label-default" id="span"></span>
<button type="submit" class="btn btn-default">Edit Name</button>
<button type="submit" class="btn btn-default">Disable</button>
<button type="submit" class="btn btn-default">Delete Group</button></h4>
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter your keyword" id="addKeyword">
<span class="input-group-btn">
<button class="btn btn-default" type="button" >Add</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div>
<h4>Keywords:</h4>
<!-- <div class="keyword" id="getKeyword"></div>-->
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="stylesheets/bootstrap.min.js"></script>
<script src="stylesheets/bootstrap.js"></script>
</body>
</html>
Basically, you have two options:
1) Save the information server side: After creating a button, make an AJAX Call to the server, save the configuration there somehow and alter the delivered html accordingly the next time this document is requested
2) Save the button configuration client side: E.g. very simple via localStorage and integrate a check into your page to check the LS for potentially created buttons.

Categories

Resources