python flask crud mysql - mysql

I am from Java background, learning Python. Please review my code and guide me to learn Python properly.
This is a sample code to perform all CRUD operation. i need some advice on my code right here, i dont know what the error and im not quite sure if this code is correct or not. this is the html and below is app.py
{% extends 'layout.html' %}
{% block body %}
<style type="text/css">
body {
color: #404E67;
background: #F5F7FA;
font-family: 'Open Sans', sans-serif;
}
.table-wrapper {
width: 1300px;
margin: 30px auto;
background: #fff;
padding: 10px;
box-shadow: 0 1px 1px rgba(0,0,0,.05);
}
.table-title {
padding-bottom: 10px;
margin: 0 0 10px;
}
.table-title h2 {
margin: 6px 0 0;
font-size: 22px;
}
.table-title .add-new {
float: right;
height: 30px;
font-weight: bold;
font-size: 12px;
text-shadow: none;
min-width: 100px;
border-radius: 50px;
line-height: 13px;
}
.table-title .add-new i {
margin-right: 4px;
}
table.table {
table-layout: fixed;
}
table.table tr th, table.table tr td {
border-color: #e9e9e9;
}
table.table th i {
font-size: 13px;
margin: 0 5px;
cursor: pointer;
}
table.table th:last-child {
width: 100px;
}
table.table td a {
cursor: pointer;
display: inline-block;
margin: 0 5px;
min-width: 24px;
}
table.table td a.add {
color: #27C46B;
}
table.table td a.edit {
color: #FFC107;
}
table.table td a.delete {
color: #E34724;
}
table.table td i {
font-size: 19px;
}
table.table td a.add i {
font-size: 24px;
margin-right: -1px;
position: relative;
top: 3px;
}
table.table .form-control {
height: 32px;
line-height: 32px;
box-shadow: none;
border-radius: 2px;
}
table.table .form-control.error {
border-color: #f50000;
}
table.table td .add {
display: none;
}
</style>
<script type="text/javascript">
// Delete row on delete button click
$(document).on("click", ".delete", function(){
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
var id = $(this).attr("id");
var string = id;
$.post("/ajax_delete", { string: string}, function(data) {
$("#displaymessage").html(data);
$("#displaymessage").show();
});
});
// update rec row on edit button click
$(document).on("click", ".update", function(){
var id = $(this).attr("id");
var string = id;
var txtname = $("#txtname").val();
var txtdepartment = $("#txtdepartment").val();
var txtphone = $("#txtphone").val();
var txtname = $("#txtname").val();
var txtdepartment = $("#txtdepartment").val();
var txtphone = $("#txtphone").val();
var txtname = $("#txtname").val();
var txtdepartment = $("#txtdepartment").val();
var txtphone = $("#txtphone").val();
var txtname = $("#txtname").val();
var txtdepartment = $("#txtdepartment").val();
$.post("/ajax_update", { string: string,txtname: txtname, txtdepartment: txtdepartment, txtphone: txtphone}, function(data) {
$("#displaymessage").html(data);
$("#displaymessage").show();
});
});
// Edit row on edit button click
$(document).on("click", ".edit", function(){
$(this).parents("tr").find("td:not(:last-child)").each(function(i){
if (i=='0'){
var idname = 'txtname';
}else if (i=='1'){
var idname = 'txtdepartment';
}else if (i=='2'){
var idname = 'txtphone';
}else{}
$(this).html('<input type="text" name="updaterec" id="' + idname + '" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
$(this).parents("tr").find(".add").removeClass("add").addClass("update");
});
});
</script>
</head>
<body>
<div class="container">
<br>
<br>
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-8"><h2>Student <b>Details</b></h2></div>
<div class="col-sm-2">
<button type="button" class="btn btn-info add-new"><i class="fa fa-plus"></i> Add New</button>
</div>
<div class='btn btn-info' id="displaymessage" style="display:none;width:100%;margin-top:10px;"></div>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>Student Name</th>
<th>Student ID</th>
<th>Faculty</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Postcode</th>
<th>Vehicle Type</th>
<th>Vehicle Brand</th>
<th>Vehicle Number Plate</th>
<th>Vehicle Image</th>
</tr>
</thead>
<tbody>
{% for row in student %}
<tr>
<td>{{row.studentname}}</td>
<td>{{row.studentid}}</td>
<td>{{row.faculty}}</td>
<td>{{row.address}}</td>
<td>{{row.city}}</td>
<td>{{row.state}}</td>
<td>{{row.postcode}}</td>
<td>{{row.vtype}}</td>
<td>{{row.vbrand}}</td>
<td>{{row.studnumplate}}</td>
<td>{{row.image}}</td>
<td>
<a class="add" title="Add" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-user-plus"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-pencil"></i></a>
<a class="delete" title="Delete" data-toggle="tooltip" id="{{row.id}}"><i class="fa fa-trash-o"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>
i already try youtube and google but i dont quite understand how to make this crud working
#app.route("/pythonlogin/editstud",methods=["POST","GET"])
def editstud():
msg = ''
if request.method == 'POST':
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM registerstud ORDER BY id')
studentname = cursor.fetchall()
if request.method == 'POST':
string = request.form['string']
studentname = request.form['studentname']
studentid = request.form['studentid']
faculty = request.form['faculty']
address = request.form['address']
city = request.form['city']
state = request.form['state']
postcode = request.form['postcode']
vtype = request.form['vtype']
vbrand = request.form['vbrand']
studnumplate = request.form['studnumplate']
image = request.form['image']
print(string)
cursor.execute("UPDATE registerstud SET studentname = %s, studentid = %s, faculty = %s, address = %s, city = %s, faculty = %s, state = %s, postcode = %s, vtype = %s, vbrand = %s, studnumplate = %s, image = %s WHERE id = %s ", [studentname, studentid, faculty, address, city, state, postcode, vtype, vbrand, studnumplate, image])
mysql.connection.commit()
cursor.close()
msg = 'Record successfully Updated'
return jsonify(msg)
return render_template('editstud.html', msg=msg)

Related

Unclickable links on <li> items in search box

I am trying to make the search results for list items in search bar hyperlinked and clickable. Looking at the coding I can't see why... This is the coding as I have figured out thus far:
<!DOCTYPE html>
<html>
<style>
.filterDiv {
float: left;
background-color: #e42625;
color: #ffffff;
width: 200px;
line-height: 100px;
text-align: center;
margin: 2px;
display: none;
}
.show {
display: block;
}
.container {
margin-top: 20px;
overflow: hidden;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: #050505;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
</style>
<body>
<h2>Ideas for A Fair Deal for Housing</h2>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')"> Show all</button>
<button class="btn" onclick="filterSelection('A')"> A</button>
<button class="btn" onclick="filterSelection('B')"> B</button>
<button class="btn" onclick="filterSelection('C')"> C</button>
<button class="btn" onclick="filterSelection('E')"> E</button>
<button class="btn" onclick="filterSelection('G')"> G</button>
<button class="btn" onclick="filterSelection('H')"> H</button>
<button class="btn" onclick="filterSelection('L')"> L</button>
<button class="btn" onclick="filterSelection('N')"> N</button>
<button class="btn" onclick="filterSelection('O')"> O</button>
<button class="btn" onclick="filterSelection('P')"> P</button>
<button class="btn" onclick="filterSelection('T')"> T</button>
<button class="btn" onclick="filterSelection('V')"> V</button>
<button class="btn" onclick="filterSelection('W')"> W</button>
<button <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myUL {
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}
</style>
</head>
<body>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for organisation.." title="Type in a name">
<ul id="myUL">
<li>A2 Dominion</li>
<li>Google</li>
<li>Bing</li>
</ul>
<script>
var UL = document.getElementById("myUL");
// hide the list by default
UL.style.display = "none";
var searchBox = document.getElementById("myInput");
// show the list when the input receive focus
searchBox.addEventListener("focus", function(){
// UL.style.display = "block";
});
// hide the list when the input receive focus
searchBox.addEventListener("blur", function(){
UL.style.display = "none";
});
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
ul = document.getElementById("myUL");
filter = input.value.toUpperCase();
// if the input is empty hide the list
if(filter.trim().length < 1) {
ul.style.display = "none";
return false;
} else {
ul.style.display = "block";
}
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
// This is when you want to find words that contain the search string
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
// This is when you want to find words that start the search string
/*if (a.innerHTML.toUpperCase().startsWith(filter)) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}*/
}
}
</script>
</body>
</html>
</button>
</div>
<div class="container">
<div class="filterDiv A">A2 Dominion</div>
<div class="filterDiv B">BPHA</div>
<div class="filterDiv W">WHG</div>
<div class="filterDiv N">Notting Hill Genesis</div>
<div class="filterDiv A">Accent</div>
<div class="filterDiv H">Housing 21</div>
<div class="filterDiv E">EMH Group</div>
<div class="filterDiv A">Anchor</div>
<div class="filterDiv G">Great Places</div>
<div class="filterDiv P">Paradigm</div>
<div class="filterDiv B">Bromford</div>
<div class="filterDiv L">Livewest</div>
<div class="filterDiv T">Thirteen</div>
<div class="filterDiv C">Citizen</div>
<div class="filterDiv H">Hyde</div>
<div class="filterDiv O">Optivo</div>
<div class="filterDiv V">Vivid</div>
</div>
<script>
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
}
}
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>
</body>
</html>
While trying to resolve this the only searchable terms are A2 Dominion, Google and Bing!
Any guidance would be very helpful. I have also made it so that the list is hidden unless the term is searched for
Thank you in advance!
epascarello answered this in a comment:
because you find the options as soon as blur is called. So when you click the blur is triggered, the options hide, you click nothing.

add color picker on top of an appended child

So I have a script that will add a text box and I want to add on top of that text box a color wheel
also I'm using electron if this helps. Any help is appreciated!
<input class="addcommandbtn" type="button" id="addCommand" style="width: 6.5%;" value="+ Command">
<select name="commandslist" id="commandslist" size="18%" style="height: 59%;width: 15%; display: block; border: 1px solid #dcdcdc; border-radius: 6px; margin-top: 5px;"></select>
<script>
function createCommandField() {
var input = document.createElement('option');
input.style.marginTop = "1%";
input.textContent = "command";
input.name = 'Commands[]';
input.style.display = 'block'
input.style.boxShadow = 'inset 0px 1px 0px 0px #ffffff';
input.style.border = '1px solid #dcdcdc';
input.style.borderRadius = '6px';
input.style.height = "2%";
input.style.padding = '5px 30px';
input.style.fontFamily = "Arial";
input.style.fontWeight = "bold";
input.style.fontSize = "17px";
return input;
}
var select = document.getElementById('commandslist');
document.getElementById('addCommand').addEventListener('click', function (e) {
select.appendChild(createCommandField());
});
</script>
here is a jquery script to get the color input changed on EDITED: selected option double click
added a function to apply selected color on the background of the same selection and un-select it to c the effect,
goodluck,
function createCommandField() {
var input = document.createElement('option');
input.style.marginTop = "1%";
input.textContent = "command";
input.name = 'Commands[]';
input.style.display = 'block'
input.style.boxShadow = 'inset 0px 1px 0px 0px #ffffff';
input.style.border = '1px solid #dcdcdc';
input.style.borderRadius = '6px';
input.style.height = "2%";
input.style.padding = '5px 30px';
input.style.fontFamily = "Arial";
input.style.fontWeight = "bold";
input.style.fontSize = "17px";
return input;
}
$(document).ready(function() {
var bgclr ='';
var parentopt = $('#pckrbg');
$('#commandslist').change(function() {
var crntslct = $('#commandslist').children('option:selected');
crntslct.dblclick(function() {
parentopt.click();
parentopt.change(function(){
bgclr = parentopt.val();
$('#commandslist').prop("selectedIndex", function(){
$(this).children('option:selected').css("background", bgclr); //set background
$(this).children('option:selected').prop("selected", false); //deselect option;
});
});
});
});
});
var select = document.getElementById('commandslist');
document.getElementById('addCommand').addEventListener('click', function(e) {
select.appendChild(createCommandField());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span><input type="color" value="#FFEE00" id="pckrbg" name="colorz" style="position:relative; display:none; float:left; margin-right:1rem; bottom:3px;"></span>
<form class="myformclass" style="font-family: sans-serif;font-size:20px;" id="myForm" onsubmit="return validateForm()">
<input class="addcommandbtn" type="button" id="addCommand" style="width: 6.5%;" value="+ Command">
<input class="addcommandbtn" type="button" id="removeCommand" style="width: 7.2%;" value="- Command" onclick="removeCommandFunc()">
<input class="savebtn" type="button" id="saveCommands" style="width: 4%; float: right;" value="Save" onclick="SaveToLocalStorage()">
<!-- Retrive Button <input class="Retrive" type="button" id="Callback" value="Retrive From LocalStorage" style="float:right;margin-right:3rem;" > -->
<select name="commandslist" id="commandslist" size="5%" style="width: 50%; display: block; border: 1px solid #dcdcdc; border-radius: 6px; margin-top: 5px;"></select>
<select name="resplist" id="resplist" size="18%" style="height: 20%;width: 59%; display: block; border: 1px solid #dcdcdc; border-radius: 6px; margin-top: 5px; margin-left: 20%;"></select>
</form>

How can I eliminate the small extra column on the right and the extra row on the bottom of my html table

I have a csv file that I load into an 11 column html table. The data displays as expected except there is a very narrow column on the far right. There is also an extra blank row at the bottom. I have made dozens of adjustments to the width percentages but the little column on the right prevails. I haven't tried to eliminate the extra row on the bottom because I don't know what to try. See CSS code.
<title>CSV to HTML5</title>
<style type="text/css">
table {
width: 850px;
display: block;
margin-left: auto;
margin-right: auto;
border: 1px solid black;
border-collapse: collapse;
}
th {
text-align: center;
padding: 6px;
border: 1px solid black;
border-collapse: collapse;
}
tr {
height: 24px;
border: 1px solid black;
}
tr:nth-child(even) {
background-color: #00FFFF;
}
td {
font-family: Arial, Verdana;
font-size: 0.8em;
font-weight: 700;
}
td {
border: 1px solid black;
cellpadding: 3px;
}
td:nth-child(1) {
width: 4%;
text-align: center;
}
td:nth-child(2) {
width: 6%;
text-align: left;
padding-left: 5px;
}
td:nth-child(3) {
width: 14%;
text-align: left;
padding-left: 5px;
}
td:nth-child(4) {
width: 14%;
text-align: left;
padding-left: 5px;
}
td:nth-child(5) {
width: 18%;
text-align: left;
padding-left: 5px;
}
td:nth-child(6) {
width: 6%;
padding-left: 5px;
}
td:nth-child(7) {
width: 5%;
text-align: center;
}
td:nth-child(8) {
width:8%;
text-align: center;
}
td:nth-child(9) {
width: 8%;
text-align: center;
}
td:nth-child(10) {
width: 8%;
text-align: center;
}
td:nth-child(11) {
width:8%;
text-align: center;
</style>
</head>
<body>
<div>
<div>
<legend>
<h1 id="clubname" style="text-align:center"></h1>
<h2 id="racename" style="text-align:center"></h2>
<h3 id="racedate" style="text-align:center"></h3>
</legend>
</div>
<div id="output">
</div>
<div id="myDiv" class="container">
<hr>
<form>
<div class="form-group">
<input type="text" class="form-control" id="inp_clubname" placeholder="Club Name" size="24" required>
<input type="text" class="form-control" id="inp_racename" placeholder="Race Name" size="24" required>
<input type="date" class="form-control" id="inp_racedate" placeholder="Date Name" size="24" required>
<label for="csvFileInput">CSV File: </label>
<input type="file" id="csvFileInput" onchange=accept=".csv" size="35" required>
<input type="button" class="btn btn-primary" onclick="generate()" value="Generate" />
</div>
</form>
<hr>
</div>
</div>
<footer>
<p style="text-align:center">©: Klexy Soft</p>
</footer>
<script type="text/javascript">
function generate() {
console.log('generate called')
//copy text from form to headings
ids = ["clubname", "racename", "racedate"]
for (i in ids) {
value = document.getElementById('inp_' + ids[i]).value
document.getElementById(ids[i]).innerHTML = value
}
files = document.getElementById('csvFileInput').files
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsText(files[0]);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
} else {
alert('FileReader is not supported in this browser.');
}
}
function loadHandler(event) {
var csv = event.target.result;
processData(csv);
}
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
for (var i = 0; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
lines.push(data);
}
//console.log(lines);
drawOutput(lines);
}
function errorHandler(evt) {
if (evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
function drawOutput(lines) {
//Clear previous data
document.getElementById("output").innerHTML = "";
var table = document.createElement("table");
for (var i = 0; i < lines.length; i++) {
var row = document.createElement("TR");
table.appendChild(row)
for (var j = 0; j < lines[i].length; j++) {
// first row is header
cell = document.createElement(i == 0 ? "TH" : "TD");
row.appendChild(cell)
cell.appendChild(document.createTextNode(lines[i][j]));
}
}
document.getElementById("output").appendChild(table);
document.getElementById("myDiv").style.visibility = "hidden";
}
console.log('initialized')
</script>
</body>
csv file
PL,Sail#,Yacht,Type,Skipper,Club,Rtg,Finish,Elapsed,Cor'ted, 1st +,
1,1234,Boat Name,42MkII,Name,GYC,115,14:10:53,02:00:53,01:46:42,00:00:00,
2,1234,Boat Name,4000,Name,GYC,107,14:16:29,02:06:29,01:53:17,00:06:35,
3,1234,Boat Name,Catalina36MKII,Name,GYC,144,14:26:34,02:16:34,01:58:48,00:12:06,
4,1234,Boat Name,42,Name,GYC,131,14:26:37,02:16:37,02:00:28,00:13:46,
5,1234,Boat Name,Mark3,Name,GYC,218,14:52:01,02:42:01,02:15:08,00:28:26,
6,1234,Boat Name,Nonsuch 30C,Name,GYC,156,14:54:43,02:44:43,02:25:29,00:38:47,
7,1234,Boat Name,KP44,Name,GYC,168,15:25:50,03:15:50,02:55:07,01:08:25,
One of the problems I was having was the java script, function drawOutput(lines) { and the codes that perform the function, generates the table and adds an extra blank row at the bottom, I guess waiting for another line of data. By adding one more line to the java script function code, the very last line, I was able to remove the extra empty row.
document.getElementById("output").appendChild(table).deleteRow(-1);

Cannot remove padding in table

I am trying to remove the padding from the cells inside my table. I have set it to not have padding in the relevant CSS selectors but not a success.
As you can see, there is padding on all of these cells.
I would like there to not be. I have tried various different padding settings and changing the vertical alignment makes no difference other than to move the text, the padding just goes from all at the bottom to spread between bottom and top.
Below is the code:
'use strict'
let table = document.getElementById("mainTable")
let rows = table.querySelectorAll("tbody tr")
let columns = table.querySelectorAll("#weeks th")
for (let row of rows) {
for (let o = 0; o<columns.length-1; o++) {
let cell = document.createElement("td")
cell.innerHTML='&nbsp'
cell.addEventListener("click", function() {
if (cell.getElementsByTagName("input")[0]) { return } //If cell currently has an input box
//
let oldValue = ""
if (cell.innerHTML !== " ") { //if cell has a saved value
oldValue = cell.innerHTML
}
cell.innerHTML = '<input type="text" class="cellInputs">'
//update input box with old value and focus it
cell.getElementsByTagName("input")[0].focus()
cell.getElementsByTagName("input")[0].value = oldValue
cell.getElementsByTagName("input")[0].addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
cell.innerHTML=cell.getElementsByTagName("input")[0].value
e.preventDefault()
return true
}
})
cell.getElementsByTagName("input")[0].addEventListener("input", function(e) {
console.log(e)
let cellValue = cell.getElementsByTagName("input")[0].value
if (e.data === "." && (cellValue.split('.').length-1 > 1 || cellValue === ".")) {
console.log("stop")
cell.getElementsByTagName("input")[0].value = (cellValue).substring(0, cellValue.length - e.data.length)
}
if (isNaN(e.data) && e.data !==".") {
console.log("Stop")
cell.getElementsByTagName("input")[0].value = (cellValue).substring(0, cellValue.length - e.data.length)
}
//store value inputted into the actual cell
})
cell.getElementsByTagName("input")[0].addEventListener("paste", function(e) {
// clipboardData = e.clipboardData || window.clipboardData;
// pastedData = clipboardData.getData('Text');
let cellValue = cell.getElementsByTagName("input")[0].value
if (cellValue !== "") {
e.preventDefault()
return false
}
if (e.clipboardData.getData('text') === "." && (cellValue.split('.').length-1 > 1 || cellValue === ".")) {
e.preventDefault()
return false
}
if (isNaN(e.clipboardData.getData('text')) && e.clipboardData.getData('text') !==".") {
e.preventDefault()
return false
}
//store value inputted into the actual cell
})
cell.getElementsByTagName("input")[0].addEventListener("focusout", function() {
console.log(document.activeElement)
cell.innerHTML=cell.getElementsByTagName("input")[0].value
})
})
row.appendChild(cell)
}
}
*{
padding: 0;
margin: 0;
font-family: "Trebuchet MS", Times, serif;
box-sizing:border-box;
}
html{
background-color: #35454E;
overflow: hidden;
}
html *{
font-family: "Work Sans", Arial, sans-serif !important;
color: white !important;
}
table{
border-collapse: collapse;
border-spacing: 0px;
color:#35454E;
height:100%;
width:100%;
}
table, th{
border: 2px solid white;
padding:0;
}
th{
vertical-align:top;
font-size: 2.5vw;
}
td{
vertical-align:top;
box-sizing:border-box;
position: relative;
border: 2px solid white;
padding:0;
text-align: center;
font-size: 2.5vw;
padding:0;
}
.cellInputs{
position: absolute;
width:100%;
height:100%;
display: block;
top:0;
left:0;
border:none;
text-align: center;
background-color: #35454E;
word-wrap: break-word;
font-size: 2.5vw;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="MMS.css">
<title>Money Management</title>
</head>
<body>
<table id="mainTable">
<thead>
<tr>
<th>2019</th>
<th colspan="5">January</th>
</tr>
<tr id="weeks">
<th>&nbsp</th>
<th>31/12/2018</th>
<th>07/01/2019</th>
<th>14/01/2019</th>
<th>21/01/2019</th>
<th>28/01/2019</th>
</tr>
</thead>
<tbody>
<tr>
<th>Balance</th>
</tr>
<tr>
<th>Pay</th>
</tr>
<tr>
<th>&nbsp</th>
</tr>
<tr>
<th>Rent</th>
</tr>
<tr>
<th>Food</th>
</tr>
<tr>
<th>&nbsp</th>
</tr>
<tr>
<th>Total</th>
</tr>
</tbody>
</table>
</body>
<script src="MMS.js"></script>
</html>
Remove height:100% from table .

How to display additional information in Google Maps autocomplete suggestions?

I am using Google Places autocomplete to select cities by name. Currently it displays only the city name and the country it belongs to, in the suggestions drop down.
I have checked and found that the "address_components" object, that gets populated when a city is selected, has additional attibutes like state/province and other parts of the address. So, it is clear that the Google's API provide additional information other than merely the city and country names.
What I am trying to achieve is, displaying a couple of those additional data in the suggestions dropdown.
Is there a way to do that?
(I have marked on the screenshot where I need to display the additional attributes)
Here is the code.
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete&query=locality" async defer></script>
<script>
var searchBox;
function initAutocomplete() {
var options = {types: ['(cities)']};
var input = document.getElementById('placeAuto');
searchBox = new google.maps.places.Autocomplete(input);
searchBox.addListener('place_changed', fillInAddress);
}
function fillInAddress()
{
var place = searchBox.getPlace();
console.log(place);
}
</script>
As I commented already, you can do that by using the Autocomplete and Places services and the getPlacePredictions method, but I would not recommend this approach as it will make a high number of requests to the API (one for each result, each time a user types something in the address field).
View the snippet in full screen mode as it won't fit hereunder or check it on JSFiddle.
In this example I have added the place latitude and longitude in the autocomplete results.
var autocompleteService, placesService, results, map;
function initialize() {
results = document.getElementById('results');
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(50, 50)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Bind listener for address search
google.maps.event.addDomListener(document.getElementById('address'), 'input', function() {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
});
// Show results when address field is focused (if not empty)
google.maps.event.addDomListener(document.getElementById('address'), 'focus', function() {
if (document.getElementById('address').value !== '') {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
}
});
// Hide results when click occurs out of the results and inputs
google.maps.event.addDomListener(document, 'click', function(e) {
if ((e.target.parentElement.className !== 'pac-container') && (e.target.parentElement.className !== 'pac-item') && (e.target.tagName !== 'INPUT')) {
results.style.display = 'none';
}
});
autocompleteService = new google.maps.places.AutocompleteService();
placesService = new google.maps.places.PlacesService(map);
}
// Get place predictions
function getPlacePredictions(search) {
autocompleteService.getPlacePredictions({
input: search,
types: ['geocode']
}, callback);
}
// Place search callback
function callback(predictions, status) {
// Empty results container
results.innerHTML = '';
// Place service status error
if (status != google.maps.places.PlacesServiceStatus.OK) {
results.innerHTML = '<div class="pac-item pac-item-error">Your search returned no result. Status: ' + status + '</div>';
return;
}
// Build output for each prediction
for (var i = 0, prediction; prediction = predictions[i]; i++) {
// Get place details to inject more details in autocomplete results
placesService.getDetails({
placeId: prediction.place_id
}, function(place, serviceStatus) {
if (serviceStatus === google.maps.places.PlacesServiceStatus.OK) {
// Create a new result element
var div = document.createElement('div');
// Insert inner HTML
div.innerHTML += '<span class="pac-icon pac-icon-marker"></span>' + place.adr_address + '<div class="pac-item-details">Lat: ' + place.geometry.location.lat().toFixed(3) + ', Lng: ' + place.geometry.location.lng().toFixed(3) + '</div>';
div.className = 'pac-item';
// Bind a click event
div.onclick = function() {
var center = place.geometry.location;
var marker = new google.maps.Marker({
position: center,
map: map
});
map.setCenter(center);
}
// Append new element to results
results.appendChild(div);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
body,
html {
font-family: Arial, sans-serif;
padding: 0;
margin: 0;
height: 100%;
}
#map-canvas {
height: 150px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
margin-left: 20px;
}
table td {
padding: 3px 5px;
}
label {
display: inline-block;
width: 160px;
font-size: 11px;
color: #777;
}
input {
border: 1px solid #ccc;
width: 170px;
padding: 3px 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
}
.pac-container {
background-color: #fff;
z-index: 1000;
border-radius: 2px;
font-size: 11px;
box-shadow: 0 2px 6px rgba(0, 0, 0, .3);
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
width: 350px;
}
.pac-icon {
width: 15px;
height: 20px;
margin-right: 7px;
margin-top: 6px;
display: inline-block;
vertical-align: top;
background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
background-size: 34px;
}
.pac-icon-marker {
background-position: -1px -161px;
}
.pac-item {
cursor: pointer;
padding: 0 4px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
line-height: 30px;
vertical-align: middle;
text-align: left;
border-top: 1px solid #e6e6e6;
color: #999;
}
.pac-item:hover {
background-color: #efefef;
}
.pac-item-details {
color: lightblue;
padding-left: 22px;
}
.pac-item-error,
.pac-item-error:hover {
color: #aaa;
padding: 0 5px;
cursor: default;
background-color: #fff;
}
<div id="map-canvas"></div>
<table>
<tr>
<td>
<label for="address">Address:</label>
</td>
</tr>
<tr>
<td>
<input id="address" placeholder="Enter address" type="text" tabindex="1" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="results" class="pac-container"></div>
</td>
</tr>
</table>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>