I'm trying to populate a table with JSON data file but that will happen when I choose an option from select options because each one of them refers to a different JSON data file, what happens is that only the Header of the table that showed beacuse it's already in the html part.
this what I get
this how it should look like
this how my code look like
$('#mySelect').change(function() {
if ($(this).val() === 'poly') {
$("#table").show();
get_json_data('poly.json');
}
else{
$("#table").show();
get_json_data('mono.json');
}
});
function get_json_data(json_url) {
// var json_url = 'example.json';
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
console.log(data);
append_json(data);
}
}
xmlhttp.open("POST", json_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function append_json(data) {
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML =
'<td > <input type="radio" value ="' + object.RendementDuPanneau + '" name="choice" /> </td>' +
'<td>' + object.Fournisseur + '</td>' +
'<td>' + object.Modele + '</td>' +
'<td>' + object.PuissanceMaximale + '</td>' +
'<td>' + object.RendementDuPanneau + '</td>';
table.appendChild(tr);
});
var elements = document.getElementsByTagName('tr');
for (var i = 0; i < elements.length; i++) {
(elements)[i].addEventListener("click", function() {
const rb = this.querySelector('input[name="choice"]');
rb.checked = true;
let selectedValue = rb.value;
alert(selectedValue);
});
}
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 400px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #202529;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
table {
border: 2px solid #ccc;
border-collapse: collapse;
margin: 0;
padding: 0;
width: 100%;
table-layout: fixed;
}
.my-custom-scrollbar {
position: relative;
height: 200px;
overflow: auto;
}
.table-wrapper-scroll-y {
display: block;
}
table thead th ,table tbody td
{
font-size : 12px;
}
tr:hover{
background-color:gray;
cursor:pointer;
}
table tbody td, table thead th {
text-align: center;
}
table tbody td:last-child, table thead th:last-child {
border-right: none;
}
table tbody td:first-child, table thead th:first-child {
width: 15px;
border-right: none;
}
table tbody td:nth-child(2), table thead th:nth-child(2) {
width: 100px;
border-left: none;
}
table tbody td:nth-child(3), table thead th:nth-child(3) {
width: 150px;
}
table tbody td:nth-child(4), table thead th:nth-child(4) {
width: 80px;
}
table tbody td:nth-child(5), table thead th:nth-child(5) {
width: 100px;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Nunito:400,300' rel='stylesheet' type='text/css'>
<form action="index.html" method="post" id="formName" name="calculeForm">
<div id="selecttype" >
<legend>Type de panneau : </legend>
<select id="mySelect" name="typeP" >
<optgroup label="Votre Type De Panneau"></optgroup>
<option></option>
<option value="poly">Silicium polycristallin</option>
<option value="mono">Silicium monocristallin</option>
</select>
</div> <br>
<div class="table-wrapper-scroll-y my-custom-scrollbar" id="table" style="display:none;">
<table class="table table-bordered table-striped mb-0" id="gable">
<thead>
<tr>
<th></th>
<th>Fournisseur</th>
<th>Modèle</th>
<th>Puissance maximale</th>
<th>Rendement du panneau</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
this how my data look like
poly.json
[{"Fournisseur":"Jinko Solar","Modele":"JKM270PP-60","PuissanceMaximale":270,"RendementDuPanneau":"16,50"},{"Fournisseur":"Jinko Solar","Modele":"JKM275PP-60","PuissanceMaximale":275,"RendementDuPanneau":"16,80"},{"Fournisseur":"Jinko Solar","Modele":"JKM280PP-60","PuissanceMaximale":280,"RendementDuPanneau":"17,11"},{"Fournisseur":"Jinko Solar","Modele":"JKM285PP-60","PuissanceMaximale":285,"RendementDuPanneau":"17,41"},{"Fournisseur":"Jinko Solar","Modele":"JKM320PP-72","PuissanceMaximale":320,"RendementDuPanneau":"16,49"}]
mono.json
[{"Fournisseur":"Risen Energy","Modele":"RSM120-6-310P","PuissanceMaximale":310,"RendementDuPanneau":"18,40%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-315P","PuissanceMaximale":315,"RendementDuPanneau":"18,70%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-320P","PuissanceMaximale":320,"RendementDuPanneau":"19,00%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-325P","PuissanceMaximale":325,"RendementDuPanneau":"19,30%"},{"Fournisseur":"Risen Energy","Modele":"RSM120-6-330P","PuissanceMaximale":330,"RendementDuPanneau":"19,60%"}]
Related
I have displayed my array of objects using dom manipulation. but it seems there is something wrong with the toggle function that i have called to the buttons.
i require each button to switch from "read" to "not read" but it only works for the first object displayed. the second one toggles the first but doesn't toggle itself? could i please get an explanation as well
let clicked = false;
function toggle(){
if(!clicked){
clicked = true;
document.getElementById("readbtn").innerHTML = "Not read";
}
else{
clicked = false;
document.getElementById("readbtn").innerHTML = "Read";
}
}
function Book(name, author, ReadOrNot) {
this.name = name
this.author = author
this.ReadOrNot = ReadOrNot
}
const book1 = new Book("The Hobbit", "J.R.R Tolkien", "Read")
const book2 = new Book("A Game of Thrones", "George R.R. Martin", "Not read")
let myLibrary = []
function addBookToLibrary(...arr) {
myLibrary.push(...arr)
}
addBookToLibrary(book1)
addBookToLibrary(book2)
console.log(myLibrary)
function addBookToTable(){
let tbody = document.querySelector('tbody')
myLibrary.forEach(b =>{
let tr = document.createElement('tr')
let content = '<td>' + b.name + '</td><td>' + b.author + '</td>'
if(b.ReadOrNot == 'Read'){
content += '<td><button id="readbtn" class="btn rdbtn" onclick="toggle()">Read</button></td>'
}
else if(b.ReadOrNot == 'Not read'){
content += '<td><button id="readbtn" class="btn rdbtn" onclick="toggle()">Not read</button></td>'
}
content += '<td><button class="btn delbtn">Delete</button></td>'
tr.innerHTML = content
tbody.appendChild(tr)
})
}
addBookToTable()
*{
box-sizing: border-box;
--darkblue: #465c6b;
--blue: #779bb3;
--lightgrey: rgb(244, 242, 242);
}
table{
border-collapse: collapse;
width: 30em;
background-color: white;
border-radius: 5px;
box-shadow: 0px 10px 30px 5px rgba(0,0,0,.15);
margin: 100px auto;
}
table thead td{
background-color: rgb(38, 36, 36);
color: whitesmoke;
border-bottom: .5px solid black;
font-size: 15px;
letter-spacing: 1px;
padding: 8px;
}
table tbody td {
padding: 8px;
}
table tbody tr td:nth-child(4){
text-align: center;
}
table tbody tr td:nth-child(3){
text-align: center;
}
table thead tr td:nth-child(3){
text-align: center;
}
table td{
font-size: 18px;
color: rgb(38, 36, 36);
}
.btn.delbtn{
background-color: #990026;
min-width: 100px;
}
<table>
<thead>
<tr>
<td>Name</td>
<td>Author</td>
<td>Status</td>
<td> </td>
</tr>
</thead>
<tbody>
</tbody>
</table>
So I'm just learning how to make a clickable grid using Jquery and I have difficulty in finding how to make each block to change colors on click. I was attempting to add a class to each through the addClass method. My main difficulty is to find each to incorporate an onclick or changeColor method.
$('body').on('click', 'td', changeColor());
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
var cell = "<td> </td>";
grid += cell;
}
grid += "</tr>";
}
$("#tableContainer").empty();
$("#tableContainer").append(grid);
return grid;
}
function changeColor() {
this.addClass("clicked");
}
body {
background-color: whitesmoke;
}
#tableContainer {
display: table;
padding: 1px;
margin-right: auto;
margin-left: auto;
}
td {
border: 1px solid;
width: 50px;
height: 50px;
padding: .5px;
background-color: skyblue;
display: table-cell;
align-items: center;
cursor: pointer;
}
td:hover {
display: block;
width: 100%;
background-color: grey;
}
.clicked {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="a3.css">
<script src="a3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<body>
<!-- <input type = "button" id="bClick" onclick="myFunction()"> -->
Rows: <input type="number" name="Rows" id="Rows"><br> Columns: <input type="number" name="Columns" id="Columns"><br> Mines: <input type="number" name="mines"> <br><br>
<button onclick="generateGrid(document.getElementById('Rows').value, document.getElementById('Columns').value)"> Click for Grid </button>
<div id="tableContainer"></div>
</body>
</html>
You are executing the function you're passing as the event handler argument so remove the ().
$(document.body).on('click', 'td', changeColor);
Then you will be able to use this in the handler.
function changeColor() {
const $this = $(this);
if ($this.hasClass("clicked")) {
$this.removeClass("clicked")
} else {
$this.addClass("clicked");
}
}
$(document.body).on('click', 'td', changeColor);
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
var cell = "<td> </td>";
grid += cell;
}
grid += "</tr>";
}
$("#tableContainer").empty();
$("#tableContainer").append(grid);
return grid;
}
function changeColor() {
const $this = $(this);
if ($this.hasClass("clicked")) {
$this.removeClass("clicked")
} else {
$this.addClass("clicked");
}
}
body {
background-color: whitesmoke;
}
#tableContainer {
display: table;
padding: 1px;
margin-right: auto;
margin-left: auto;
}
td {
border: 1px solid;
width: 50px;
height: 50px;
padding: .5px;
background-color: skyblue;
display: table-cell;
align-items: center;
cursor: pointer;
}
td:hover {
display: block;
width: 100%;
background-color: grey;
}
.clicked {
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="a3.css">
<script src="a3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<!-- <input type = "button" id="bClick" onclick="myFunction()"> -->
Rows: <input type="number" name="Rows" id="Rows"><br> Columns: <input type="number" name="Columns" id="Columns"><br> Mines: <input type="number" name="mines"> <br><br>
<button onclick="generateGrid(document.getElementById('Rows').value, document.getElementById('Columns').value)"> Click for Grid </button>
<div id="tableContainer"></div>
</body>
</html>
Your issue here is that you are binding the click event on the td before they are ever on the page. You need to make sure to bind the click function at the bottom of your generateGrid() function, like so:
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
var cell = "<td> </td>";
grid += cell;
}
grid += "</tr>";
}
$("#tableContainer").empty();
$("#tableContainer").append(grid);
$('td').click(function(){
changeColor($(this));
});
}
function changeColor(cell) {
if(cell.hasClass('clicked')){
cell.removeClass('clicked');
} else {
cell.addClass('clicked');
}
}
body {
background-color: whitesmoke;
}
#tableContainer {
display: table;
padding: 1px;
margin-right: auto;
margin-left: auto;
}
td {
border: 1px solid;
width: 50px;
height: 50px;
padding: .5px;
background-color: skyblue;
display: table-cell;
align-items: center;
cursor: pointer;
}
td:hover {
display: block;
width: 100%;
background-color: grey;
}
td.clicked {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="a3.css">
<script src="a3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<body>
<!-- <input type = "button" id="bClick" onclick="myFunction()"> -->
Rows: <input type="number" name="Rows" id="Rows"><br> Columns: <input type="number" name="Columns" id="Columns"><br> Mines: <input type="number" name="mines"> <br><br>
<button onclick="generateGrid(document.getElementById('Rows').value, document.getElementById('Columns').value)"> Click for Grid </button>
<div id="tableContainer"></div>
</body>
</html>
He, i'm almost done with my project but i still have one problem.
when i am removing a table row dynamically, the row count is going terrible wrong. i thought i had the solution for this problem.
how should i reset the row count for the rows after a row remove.
can some one explain what i am doing wrong ?
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value - 1;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
// rework the row length
for (var i = 0; i < row.length; i++) {
rows[i].cells[0].innerText = row.length;
}
console.log(row.length, " 'row lenght' ");
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body {
background: white;
}
img {
height: 100%;
display: block;
margin: 0 auto;
}
p {
text-align: center;
}
.container {
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table {
width: 100%;
text-align: center;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100%;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red {
background: red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus {
outline: none;
color: black;
}
::-webkit-input-placeholder {
color: black;
font: helvetica 12px bold;
text-align: center;
}
select {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
Bellow Snippet will give you the answer. However there is a small error on this row remove function. The user must know row index is starting at 0 to get the 1st row. Otherwise a wrong row will be deleted.
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
row = document.getElementById("table").getElementsByTagName("tr");
// rework the row length
for (var i = 0; i < row.length; i++) {
row[i].cells[0].innerText = i+1;
}
console.log("Row length: "+ row.length);
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body {
background: white;
}
img {
height: 100%;
display: block;
margin: 0 auto;
}
p {
text-align: center;
}
.container {
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table {
width: 100%;
text-align: center;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100%;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red {
background: red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus {
outline: none;
color: black;
}
::-webkit-input-placeholder {
color: black;
font: helvetica 12px bold;
text-align: center;
}
select {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
this is my solution i don't think it is the nicest way but it works, thanks for the help with thinking Inuka.
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
// input fields Variable
var firstName = document.myForm.firstName;
var lastName = document.myForm.lastName;
var Age = document.myForm.Age;
var Country = document.myForm.Country;
var row = document.getElementById("table").getElementsByTagName("tr");
btn.onclick = function() {
addData()
};
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if (document.myForm.firstName.value == "") {
alert("Please provide your first name!");
document.myForm.firstName.focus();
return false;
}
// last name field check + error message
if (document.myForm.lastName.value == "") {
alert("Please provide your last name!");
document.myForm.lastName.focus();
return false;
}
// age field check + error message
if (isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100) {
alert("Please provide your age!");
return false;
}
// country select list check + error message
if (document.myForm.Country.value == "chooseCountry") {
alert("Please provide your country!");
return false;
}
// if evry thing is true return a value of true
return true;
}
function addData() {
if (validate()) {
// creating a new tr
var tr = document.createElement("tr");
// adding the created elements to a object with a class name
table.appendChild(tr);
var rows = " ";
rows += "<td>" + row.length + "</td><td>" + firstName.value + "</td><td>" + lastName.value + "</td><td>" + age.value + "</td><td>" + country.value + "</td>";
tr.innerHTML = rows;
//console.log(row.length, " 'row length' ");
//console.log(firstName.value, " 'firstname value' ");
//console.log(lastName.value, " 'lastName value' ");
//console.log(age.value, " 'age value' ");
//console.log(country.value, " 'country value' ");
}
}
function removeTableRow() {
var tableNr = document.getElementById("tableNr");
i = tableNr.value - 1;
// if there is no table number filled in show a error alert
if (i == "") {
alert("Please provide a table number!");
tableNr.focus();
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if (row == undefined) {
alert("this row number is not in the table");
return false;
}
// remove the selected row
row.remove(row.selectedIndex);
row = document.getElementById("table").getElementsByTagName("tr");
// rework the row length
for (var i = 0; i < row.length; i++) {
row[i].cells[0].innerText = i+1;
}
console.log("Row length: "+ row.length);
}
removeRowBtn.onclick = function() {
removeTableRow()
};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<thead>
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName" id="firstName">
<input type="text" name="lastName" placeholder="lastName" id="lastName">
<input type="text" name="Age" placeholder="Age" id="age">
<select name="Country" id="country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
I have the following form for lyrics upload. I've changed the design of the form a little bit, and now facing a weird problem.
I've created a fake-datalist using JS. On input focus, a fake-datalist (an ul element) is appended next to the input element. Its position is set to absolute so it shouldn't disrupt the flow of the document when it appears. However, it does. I can't seem to identify the problem. Once the datalist appears, the div next to the table gets pushed down. Table width isn't changing when the datalist appears, so it's not squizing the div and pushing it down.
Code Pen
var artists = [{"artist":"3 Doors Down"},{"artist":"5 Seconds of Summer"},{"artist":"Adele"},{"artist":"Alicia Keys"},{"artist":"Amanda Abizaid"},{"artist":"Avril Lavigne"}];
var albums = [{"album":"The Better Life","year":"2000","cover":"3_doors_down_2000_the_better_life.jpg"},{"album":"Away from the Sun","year":"2002","cover":"3_doors_down_2002_away_from_the_sun.jpg"},{"album":"Seventeen Days","year":"2005","cover":"3_doors_down_2005_seventeen_days.jpg"},{"album":"3 Doors Down","year":"2008","cover":"3_doors_down_2008_3_doors_down.jpg"},{"album":"Time of My Life","year":"2011","cover":"3_doors_down_2011_time_of_my_life.jpg"}];
var songs = [{"song":"Kryptonite","track_no":"1"},{"song":"Duck and Run","track_no":"3"},{"song":"Be Like That","track_no":"5"},{"song":"So I Need You","track_no":"11"}];
function datalist(element) {
return new datalist.prototype.init(element);
}
datalist.prototype = {
init: function(element) {
if (!element) {
this.element = document.createElement("ul");
this.element.classList.add("datalist");;
this.hide();
} else {
this.element = element;
}
},
update: function(queryElement) {
this.clear();
var lookUpArray = queryElement.name + "s";
var results = this.search(window[lookUpArray], queryElement.value, queryElement.name);
for (var i = 0; i < results.length; i++) {
var li = document.createElement("li");
var value = results[i][queryElement.name];
switch (queryElement.name) {
case "album":
li.setAttribute("data-year", results[i].year);
break;
case "song":
li.setAttribute("data-track_no", results[i].track_no);
break;
}
if (queryElement.value != "") {
var re = new RegExp(queryElement.value, "gi");
value = value.replace(re, "<span class=\"highlight\">" + "$&" + "</span>");
}
li.innerHTML = value;
this.element.appendChild(li);
}
return results.length;
},
search: function(lookUpArray, string, queryType) {
var results = [];
for (var i = 0; i < lookUpArray.length; i++) {
if (lookUpArray[i][queryType].toLowerCase().search(string.toLowerCase()) != -1) {
results.push(lookUpArray[i]);
}
}
return results;
},
clear: function() {
this.element.innerHTML = "";
},
hide: function() {
this.element.style.display = "none";
},
show: function() {
this.element.style.display = "";
},
remove: function() {
this.element.parentElement.removeChild(this.element);
},
for: function(sibling) {
sibling.parentElement.appendChild(this.element);
this.hide();
},
};
datalist.prototype.init.prototype = datalist.prototype;
var lastVisitedInput = null;
$("#lyrics-form").on("focus", "input.datalist-input", function() {
if (this.parentElement.children.length == 1) {
this.parentElement.appendChild(datalist().element);
}
if (lastVisitedInput) {
datalist(lastVisitedInput.nextElementSibling).hide();
}
lastVisitedInput = this;
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$(document).on("click", function(e) {
if (lastVisitedInput) {
var exceptions = getExceptions(lastVisitedInput);
if (!contains(exceptions, e.target)) {
datalist(lastVisitedInput.nextElementSibling).remove();
lastVisitedInput = null;
}
}
});
$("#lyrics-form").on("input", "input.datalist-input", function() {
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$("#lyrics-form").on("click", "li", function() {
this.parentElement.previousElementSibling.value = this.innerText;
$(this.parentElement.previousElementSibling).trigger("input");
});
function getRecord(input) {
var lookUpArray = window[input.name + "s"];
for (var i = 0; i < lookUpArray.length; i++) {
if (input.value == lookUpArray[i][input.name]) {
return lookUpArray[i];
}
}
return false;
}
function getExceptions(input) {
var exceptions = [
input,
input.nextElementSibling,
];
for (var i = 0; i < input.nextElementSibling.children.length; i++) {
exceptions.push(input.nextElementSibling.children[i]);
}
return exceptions;
}
function contains(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
return true;
}
}
return false;
}
* { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } *, *:before, *:after { box-sizing: inherit; } body { line-height: 1.5; font-family: sans-serif; } input[type="button"], input[type="submit"] { cursor: pointer; } textarea, input[type="text"], input[type="search"], input[type="number"], input[type="password"] { border: 1px solid rgba(0,0,0,.2); padding: 4px; margin: 1px; } table { border-collapse: collapse; border-spacing: 0; }
body {
background-color: rgb(230, 230, 230);
font-family: Arial, sans-serif;
font-size: 14px;
color: rgba(0, 0, 0, .8);
box-sizing: border-box;
}
#main {
height: 500px;
background: white;
box-shadow: 0 0 2px rgba(0, 0, 0, .1), 0 2px 2px rgba(0, 0, 0, .1);
margin: 20px auto;
display: table;
padding: 20px;
}
#songInput {
overflow: auto;
}
#songTable td {
position: relative;
}
#songTable,
#coverDiv {
float: left;
}
#coverDiv {
margin-left: 20px;
}
#artist,
#album,
#song {
width: 250px;
}
#artist {
width: 300px;
width: 100%;
}
#year,
#track_no {
width: 70px;
}
#songTable td {
padding-bottom: 20px;
}
#songTable td:first-child {
padding-right: 10px;
}
#songTable .int-input {
padding-left: 20px;
padding-right: 10px;
}
#coverDiv > * {
display: block;
}
#coverDiv img {
width: 137px;
height: 137px;
border: 1px solid rgba(0, 0, 0, .2);
margin: 1px;
}
#coverUpload {
margin: 1px;
margin-top: 10px;
width: 250px;
}
#lyricsBox {
width: 100%;
height: 400px;
margin-top: 15px;
}
#submit {
width: 100%;
margin-top: 15px;
}
.datalist {
border: 1px solid silver;
box-shadow: 0 2px 5px rgba(0, 0, 0, .5);
position: absolute;
top: 32px;
left: 1px;
background: white;
padding: 5px;
max-height: 195px;
width: 180px;
width: 100%;
overflow-y: scroll;
z-index: 1000;
}
.datalist li {
padding: 2px 5px;
cursor: default;
}
.datalist li:hover {
background: rgba(0, 0, 0, .05);
color: black;
}
.datalist .highlight {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<form action="addlyrics.php" id="lyrics-form" method="post" autocomplete="off" enctype="multipart/form-data">
<div id="songInput">
<table id="songTable">
<tr>
<td>Artist</td>
<td colspan="3">
<input type="search" name="artist" id="artist" class="datalist-input" placeholder="Artist" required />
</td>
</tr>
<tr>
<td>Album</td>
<td>
<input type="search" name="album" id="album" class="datalist-input" placeholder="Album" required />
</td>
<td class="int-input">Year</td>
<td>
<input type="number" name="year" id="year" class="input-num" placeholder="Year" required />
</td>
</tr>
<tr>
<td>Song</td>
<td>
<input type="search" name="song" id="song" class="datalist-input" placeholder="Name" required />
</td>
<td class="int-input">#</td>
<td>
<input type="number" name="track_no" id="track_no" class="input-num" placeholder="ID" required />
</td>
</tr>
</table>
<div id="coverDiv">
<img src="covers/blank.gif" id="cover" />
<input type="file" name="cover" id="coverUpload" accept="image/*" />
</div>
</div>
<textarea name="lyrics" placeholder="Lyrics" id="lyricsBox" /></textarea>
<input type="submit" id="submit" class="button" />
</form>
</div>
Removing overflow: auto; from #songInput, the parent element of the table and the div, solved the problem. Although, I don't understand why overflow: auto; on the parent would push the div down. Dynamically added ul.datalist's position is set to absolute, and when it appears, the only thing it might do is extend the height of the table, which shouldn't effect the div at the right.
I have created a 16x16 grid. I'm trying to put a button above the grid, which when the user clicks, will prompt them for new grid dimensions (between 1 and 64). For example, if you click the button and input 25, the dimensions of the grid will change from 16x16 to 25x25.
I'm having trouble in figuring out how to get the user's input into a javascript function, so it outputs the updated grid. Code here:
HTML:
<!doctype html>
<html>
<head>
<title>SketchPad</title>
<link rel="stylesheet" type="text/css" href="style.css" >
</head>
<body>
<h1> SketchPad </h1>
<div id="container">
</div>
<button class="button" type="button" onclick="myFunction()">Choose Your Grid</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="jquery.js"></script>
</body>
</html>
CSS:
h1 {
text-align: center;
color: black;
}
tr, td, table {
border-style: solid;
border-width: 1px;
background-color: gray;
margin: auto;
height: 25px;
width: 525px;
margin-top: 20px;
}
td {
transition: .3s background-color;
}
td:hover {
background-color: red;
}
button {
height: 25px;
width: 225px;
margin: 0 auto;
position: relative;
top: 50%;
left: 40%;
margin-top: -40px;
}
Javascript:
var rows=16;
var cols=16;
document.write("<table>");
for (i=0; i<rows; i++) {
document.write("<tr>");
for (j=0; j<cols; j++) {
document.write("<td>"+"</td>");
}
document.write("</tr>");
}
document.write("</table>");
$( "td").css("color", "red");
$(".button").click(function() {
prompt("Please select your grid size");
});
function grid(rows, cols) {
//function goes here//
}
Try something like the following.
Write a function which empties your container and redraws your grid inside it.
Initialize your grid in a document.ready() hander.
Define an event handler for your button click, which prompts to redraw the grid at a user-defined size.
$(document).ready(function() {
grid(16,16);
});
$(".button").click(function() {
var size = prompt("Please select your grid size");
grid(size, size);
});
function grid(rows, cols) {
var table = "<table>";
var size = (1 / rows * 525) + "px";
for (i=0; i<rows; i++) {
table += "<tr>";
for (j=0; j<cols; j++) {
table += "<td>"+"</td>";
}
table += "</tr>";
}
table += "</table>";
$("#container").empty().append(table);
$("tr").css("height", size);
$("td").css("color", "red").css("width", size);
}
h1 {
text-align: center;
color: black;
}
table {
height: 525px;
width: 525px;
}
tr, td, table {
border-style: solid;
border-width: 1px;
background-color: gray;
margin: auto;
margin-top: 20px;
}
td {
transition: .3s background-color;
}
td:hover {
background-color: red;
}
button {
height: 25px;
width: 225px;
margin: 0 auto;
position: relative;
top: 50%;
left: 40%;
margin-top: -40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1> SketchPad </h1>
<div id="container">
</div>
<button class="button" type="button">Choose Your Grid</button>