Complete form based on drop down selection - javascript

I have a simple form that requires employees to input phone numbers, employee ID, etc. I would like to save them some time (and prevent data entry errors) by allowing them to select their name form a drop down and have the text input fields for phone and ID number autofill based on the name selected.
I have an HTML table that contains all the employee information, but do not know how to pass that information to the proper fields. Code snippet follows:
#emp_data_tbl {
width: 90%
}
#emp_data_tbl td,
#emp_data_tbl th {
border: 1px solid #ddd;
padding: 8px;
}
#emp_data_tbl tr:nth-child(even) {
background-color: #f2f2f2;
}
#emp_data_tbl tr:hover {
background-color: #ddd;
}
#emp_data_tbl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<p>Name</p>
<select required>
<option value="" disabled selected hidden>Choose Name...
</option>
<option value="Adam Jackson">Adam Jackson
</option>
<option value="Bill Smith">Bill Smith
</option>
<option value="Chris Clinton">Chris Clinton
</option>
<option value="David Billings">David Billings
</option>
<option value="Eamon Lampsen">Eamon Lampsen
</option>
</select>
<p>Phone</p>
<input type="text" id="phone">
<p>ID</p>
<input type="text" id="IdNum">
<br><br>
<hr><br><br>
<table id="emp_data_tbl">
<caption>In reality, this data table is hidden with CSS display: none but viewable here in this mock up</caption>
<col>
<col>
<col>
<tr>
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tr>
<td>Adam Jackson</td>
<td>111-111-1111</td>
<td>#1111</td>
</tr>
<tr>
<td>Bill Smith</td>
<td>222-222-2222</td>
<td>#2222</td>
</tr>
<tr>
<td>Chris Clinton</td>
<td>333-333-3333</td>
<td>#3333</td>
</tr>
<tr>
<td>David Billings</td>
<td>444-444-4444</td>
<td>#4444</td>
</tr>
<tr>
<td>Eamon Lampsen</td>
<td>555-555-5555</td>
<td>#5555</td>
</tr>
</table>

This will get you started.
#emp_data_tbl {
width: 90%
}
#emp_data_tbl td,
#emp_data_tbl th {
border: 1px solid #ddd;
padding: 8px;
}
#emp_data_tbl tr:nth-child(even) {
background-color: #f2f2f2;
}
#emp_data_tbl tr:hover {
background-color: #ddd;
}
#emp_data_tbl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<form action="#">
<label for="name">Name</label><br>
<select id="name" name="name"></select><br><br>
<!--<label for="female">Phone</label><br>
<input type="text" name="phone" id="phone"><br><br>
<label for="id">ID</label><br>
<input type="text" name="id" id="id"><br><br>-->
<input type="submit" value="Submit">
</form>
<br><br>
<hr><br><br>
<table id="emp_data_tbl">
<tr>
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tr>
<td>Adam Jackson</td>
<td>111-111-1111</td>
<td>#1111</td>
</tr>
<tr>
<td>Bill Smith</td>
<td>222-222-2222</td>
<td>#2222</td>
</tr>
<tr>
<td>Chris Clinton</td>
<td>333-333-3333</td>
<td>#3333</td>
</tr>
<tr>
<td>David Billings</td>
<td>444-444-4444</td>
<td>#4444</td>
</tr>
<tr>
<td>Eamon Lampsen</td>
<td>555-555-5555</td>
<td>#5555</td>
</tr>
</table>
<script>
var rows = document.getElementById("emp_data_tbl").rows;
var users = [];
var phonenrs = [];
var ids = [];
//start at i = 1 to skip the header row
for(var i = 1; i < rows.length; i++)
{
users.push(rows[i].cells[0].innerHTML);
phonenrs.push(rows[i].cells[1].innerHTML);
ids.push(rows[i].cells[2].innerHTML);
}
var nameList = document.getElementById("name");
for(var i = 0; i < users.length; i++)
{
nameList.add(new Option(users[i], users[i] + " - " + phonenrs[i] + " - " + ids[i]));
}
</script>
After this, you will need to do something when your user chooses his name.
You can do this by adding an onChange to the selectbox, which holds a function that will be executed the moment the user chooses an option of the selectbox. For example:
<select id="name" name="name" onchange="fillData();"></select>
After this, you can create a Javascript function fillData(), that get's the telephone number and id, belonging to the user and fill in the values with javascript. Something like:
function fillData(){
document.getElementById("phone").value = "";
//get and set your id and phone values here
}

Related

How to show 'no results try again' on a jquery toggle search filter

I am customizing this basic jQuery Data Table with Search Filter tutorial for my own use and it works great except I can't figure out how to toggle to show a specific message when the filter returns no results: https://www.coderbench.com/develop-jquery-data-table-search-filter/
Here is the script:
$(document).ready(function(){
$("#txtsearch").keyup(function(){
var value = $(this).val().toLowerCase();
$("#table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
This works for what I need except I want to display the following text above my table when there are no row matches and all rows are toggled hidden:
<span class="warning">Your search returned no results, please modify your entry.</span>
I imagine there's some elaborate conditional statement I could make here but I'm wondering if there's a simple way to do this....as is often the case. Thanks! Here is the full sample page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#txtsearch").keyup(function(){
var value = $(this).val().toLowerCase();
$("#table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #e3e3e3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #efefef;
}
</style>
<div>
<input id="txtsearch" type="text" placeholder="Search Here..." />
<br><br>
<table>
<thead>
<tr>
<th>Movies</th>
<th>Rating</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Spiderman Homecoming</td>
<td>9/10</td>
</tr>
<tr>
<td>Wonder Woman</td>
<td>8/10</td>
</tr>
<tr>
<td>The Guardians of Galaxy 2</td>
<td>8/10</td>
</tr>
<tr>
<td>Ant Man</td>
<td>7.5/10</td>
</tr>
</tbody>
</table>
</div>
Here's my try.
I don't use jQuery much so feel free to adapt things to a more "jQuery"-way.
const warning = document.querySelector('.warning');
const table = document.querySelector('table');
$(document).ready(function() {
$("#txtsearch").keyup(function() {
let value = $(this).val().toLowerCase();
let numberOfResults = 0;
$("#table tr").filter((index, tableRow) => {
let isAMatch = $(tableRow).text().toLowerCase().indexOf(value) > -1;
$(tableRow).toggle(isAMatch);
if (isAMatch) {
numberOfResults++;
}
});
if (numberOfResults === 0) {
warning.classList.add('show')
table.classList.add('no-results');
} else {
warning.classList.remove('show');
table.classList.remove('no-results');
}
});
});
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
}
table.no-results {
display: none;
}
td,
th {
border: 1px solid #e3e3e3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #efefef;
}
.warning {
margin-bottom: 10px;
display: none;
}
.warning.show {
display: block;
}
<div>
<span class="warning">Your search returned no results, please modify your entry.</span>
<input id="txtsearch" type="text" placeholder="Search Here..." />
<br><br>
<table>
<thead>
<tr>
<th>Movies</th>
<th>Rating</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Spiderman Homecoming</td>
<td>9/10</td>
</tr>
<tr>
<td>Wonder Woman</td>
<td>8/10</td>
</tr>
<tr>
<td>The Guardians of Galaxy 2</td>
<td>8/10</td>
</tr>
<tr>
<td>Ant Man</td>
<td>7.5/10</td>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

Export html table with dropdown lists to a CSV file using jquery/javascript

As written in the title , I have HTML table that has few columns where the user has to select values from dropdown lists. What I want to do is to be able to export this table to a CSV file . I found online a jquery plugin but I have a problem with the dropdown lists. It gives back all of the option for each row instead the ones that are selected. I tried fixing this but I failed.
The JQuery plugin and and example table are in the jsfiddle:
https://jsfiddle.net/bLa8pn74/
I tried to insert this:
if($(this).find('select').each(function(){
line.push(_quote_text($(this).find("option:selected").text()));
}));
But it only printed the head row. I now it should be simple change but I just can't figure it out .
EDIT: I would like that my solution is without creating new table.
EDIT 2: I tried this code also :
if($(this).find('select')){
line.push(_quote_text($(this).find('option:selected').text()));
}
line.push(_quote_text(_trim_text($(this).text())));
And it gives me the selected option but also afterwards all dropdown options, and extra "","", where it finds an empty cell.
And If I add "else" before the second "line.push" then it returns only the selected values and everything else is empty.
I found what was missing. I just needed the ".length" in my if condition.
if($(this).find('select').length){
line.push(_quote_text($(this).find('option:selected').text()));
}else{
line.push(_quote_text(_trim_text($(this).text())));
}
Here is your working Code....
jQuery("#import").on('click', function (event) {
$('#my_id').table2csv({
file_name: 'test.csv',
header_body_space: 0
});
});
// JQuery Plugin
/**
* #description: Plugin to export HTML table to CSV file.
* #author: VenkataRamanaB
* #link: https://github.com/venkataramanab/table2csv
* Feel free to use or modify this plugin as far as my full name is kept
*/
(function ($) {
const _trim_text = (text) => {
return text.trim();
};
const _quote_text = (text) => {
return '"' + text + '"';
};
const _export = (lines, file_name) => {
const uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(lines.join('\n'));
const el_a = document.createElement('a');
el_a.href = uri;
el_a.download = file_name;
document.body.appendChild(el_a);
el_a.click();
document.body.removeChild(el_a);
};
const init = (tb, options) => {
let lines = [];
$(tb).find('thead>tr').each(function () {
let line = [];
$(this).find('th').each(function () {
line.push(_quote_text(_trim_text($(this).text())));
});
lines.push(line.splice(0).toString());
})
for (let i = 0; i < options.header_body_space; i++) lines.push('\n');
$(tb).find('tbody>tr').each(function () {
let line = [];
$(this).find('td').each(function () {
/* If <td> has <select>, CSV have selected value */
if($(this).find('select').length > 0){
var optVal = $(this).find('select').val();
var selectVal = $(this).find('option[value="'+optVal+'"]').text();
line.push(_quote_text(_trim_text(selectVal)));
}
else{
line.push(_quote_text(_trim_text($(this).text())));
}
});
lines.push(line.splice(0).toString());
})
_export(lines, options.file_name)
};
$.fn.extend({
table2csv: function (options) {
const default_options = {
file_name: 'table_records.csv',
header_body_space: 1
};
options = $.extend(default_options, options);
init(this, options);
}
})
})(jQuery);
$(function(){
var firstDDM = ['aaa','bbb','ccc','ddd'];
var firstshortcut = ['a','b','c','d'];
var option = "",
select = "";
for(var i=0; i<firstDDM.length;i++){
option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(3)").append(select);
});
});
table {
border-collapse: collapse;
border: 1px black solid;
font: 12px sans-serif;
width: 100%;
table-layout:auto;
}
td {
border: 1px black solid;
text-align: left;
padding: 2px;
}
thead:hover{
text-decoration: none !important;
}
thead tr:first-child{
color:white;
text-align: center;
background-color: #5bc0de;
padding: 10px;
}
tr:nth-child(even){
background-color: #f2f2f2
}
tr:hover{
background-color: #5bc0de;
}
button{
display: inline;
padding: 50px;
}
input button{
display: inline;
}
.dropbtn{
background-color: blue;
}
.table-responsive {
overflow-y: auto;
height: 800px;
}
.table-responsive table {
border-collapse: collapse;
width: 100%;
}
.table-responsive thead th{
position: sticky;
top: 0;
background-color: #5bc0de;
padding: 2px;
}
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
}
.myButtons{
display: inline;
padding: 20px;
}
<html>
<head>
<title>Filtered CSV File</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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 href="static/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.10.18/datatables.min.css"/>
</head>
<body>
<h1>
Filtered CSV FIle
</h1>
<br/>
<br/>
<div>
<input type="button" value="Import" class="btn btn-info" id="import">
</div>
<br/>
<div class="table-responsive">
<table class="dataframe my_class" id="my_id">
<thead>
<tr style="text-align:right;">
<th> </th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
<th>col7</th>
<th>col8</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>row1</td>
<td>row1</td>
<td>row1</td>
<td></td>
<td>row1</td>
<td><select name="code">
<option value="a">AAA</option>
<option value="b">BBB</option>
</select></td>
<td>row1</td>
<td>row1</td>
</tr>
<tr>
<th>2</th>
<td>row2</td>
<td>row2</td>
<td>row2</td>
<td></td>
<td>row2</td>
<td><select name="code">
<option value="a">AAA</option>
<option value="b">BBB</option>
</select></td>
<td>row2</td>
<td>row2</td>
</tr>
<tr>
<th>3</th>
<td>row3</td>
<td>row3</td>
<td>row3</td>
<td></td>
<td>row3</td>
<td><select name="code">
<option value="a">AAA</option>
<option value="b">BBB</option>
</select></td>
<td>row3</td>
<td>row3</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

adding dynamically the data into the columns of the table in JavaScript

function add_fields() {
document.getElementById('myTable').innerHTML += '<tr> <td> <textarea name = "Product ID" placeholder = "Product ID" style = "resize: none; width: 100%;" document.getElementById("1")></textarea></td> <td> <textarea name = "Title" placeholder = "Title" style = "resize: none; width: 100%;"></textarea></td><td> <textarea name = "startdate" placeholder = "startdate" style = "resize: none; width: 100%;"></textarea></td> </tr>';
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<div class="set-form">
<input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" />
</div>
<table id="myTable">
product id : <input type="text" name="fname" id="1"><br>
<thead>
<tr>
<th>Product ID</th>
<th>Title</th>
<th>Start Date</th>
<th>End Date</th>
<th>Excl</th>
<th>Territory</th>
<th>Media</th>
<th>Language</th>
<th>Format</th>
<th>Acquiring Division</th>
<th>Owner</th>
</tr>
</thead>
</table>
I want to add dynamically to the table by selecting the id whenever the user enters the data the data should add automatically to the table.
Is there any better way I want to add a column to the table and data to be added at once but I could not figure out so I planned the above code.
Any suggestions?
Playing a little with your code, I made the following modifications…
HTML stays in HTML, I've added a tr with id="row-type". It's hidden but the content is used to add a new tr when you click Add More. I've modified your existing function accordingly.
CSS stays in CSS, I've moved the table textarea style in the CSS.
As it's not recommended to use .innerHTML +=, I replaced it with .appendChild(…).
I've added a button in the row-type element. So that, when you click Submit, the content of the row is converted from textareas to texts.
As we're only adding in the 3 first tds, I've removed some of the other tds in the HTML to shorten the snippet. But it works exactly the same with all of it (I tried).
I've added a cancel function, in case you finally don't want to add.
…and ended-up with this working snippet:
(See comments in the code for more details)
// TAKIT: Now the content is in the HTML, append it to the current table
function add_fields() {
// TAKIT: Replaced .innerHTML as it's not recommended
var newElement = document.createElement('tr');
newElement.innerHTML = document.getElementById('row-type').innerHTML;
document.getElementById('myTable').appendChild(newElement);
}
// TAKIT: Added this function for when you click on the submit button
function put_in_table(elm) {
var tds = elm.closest('tr').children; // Get all tds of the line you just clicked "submit"
for (var i = 0; i < tds.length; i++) { // For all tds
// replace the HTML with the text value of the textarea (that removes the textareas)
if (tds[i].innerHTML)
tds[i].innerText = tds[i].children[0].value || '';
}
}
// TAKIT: Added this function to cancel the add
function cancel_add(elm) {
elm.closest('tr').outerHTML = ''; // Empty current tr
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* TAKIT: Added hidden on row type, and moved style of textareas here */
#row-type {
display: none;
}
table textarea {
resize: none;
width: 100%;
}
<div class="set-form"><input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" /></div>
<table id="myTable">
<!-- TAKIT: Added p element here, it's proper. What is it used for, by the way? -->
<p>product id : <input type="text" name="fname" id="1"></p>
<thead>
<tr>
<th>Product ID</th>
<th>Title</th>
<th>Start Date</th>
<th>End Date</th>
<th>Excl</th>
</tr>
</thead>
<tbody>
<!-- TAKIT: Added body and the "row-type" in it, so that HTML stays in HTML -->
<tr id="row-type">
<td><textarea name="Product ID" placeholder="Product ID"></textarea></td>
<td><textarea name="Title" placeholder="Title"></textarea></td>
<td><input name="startdate" type="date"></td>
<td><input name="enddat" type="date"></td>
<td>
<button onclick="put_in_table(this);">Submit</button> <button onclick="cancel_add(this);">Cancel</button>
</td>
</tr>
</tbody>
</table>
Hope it helps.
I find it easiest to just have a div/span which I write a table in dynamically with javascript, e.g.
example_array = [["Name","Age"],["Antonio","35"]];
function array_to_table(my_array){
my_table_html = '<table>';
for(var i = 0; i<my_array.length; i++){
my_table_html += "<tr>";
for(var j = 0; j < my_array[i].length; j++){
my_table_html += "<td>"+my_array[i][j]+"</td>";
}
my_table_html += "</tr>";
}
my_table_html += '</table>';
document.getElementById("mytable").innerHTML = my_table_html;
}
array_to_table(example_array);
<div id="mytable"></div>
When you have this framework for creating/updating tables, you can edit the array that's fed into the function to dynamically update your table.
Here is a working example, enter the desired values in the first row (I have only the first three elements here). Then click Add, the row will be added to the table.
function add_fields() {
// select the input values
let productId = document.querySelector('#productId').value
let title = document.querySelector('#title').value
let startDate = document.querySelector('#startDate').value
// prepare a new row
let tr = document.createElement('tr')
tr.innerHTML = `
<tr>
<td>
<div id="productId" style="resize: none; width: 100%;">${productId}</div>
</td>
<td>
<div id="title" style="resize: none; width: 100%;">${title}</div>
</td>
<td>
<div id="startDate" style="resize: none; width: 100%;">${startDate}</div>
</td>
</tr>
`
// remove content of textareas
document.querySelector('#productId').value = ''
document.querySelector('#title').value = ''
document.querySelector('#startDate').value = ''
// append a new row to the table
document.querySelector('#myTable').appendChild(tr)
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<div class="set-form">
<input type="button" id="more_fields" onclick="add_fields();" value="Add" class="btn btn-info" />
</div>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>Product ID</th>
<th>Title</th>
<th>Start Date</th>
<th>End Date</th>
<th>Excl</th>
<th>Territory</th>
<th>Media</th>
<th>Language</th>
<th>Format</th>
<th>Acquiring Division</th>
<th>Owner</th>
</tr>
<tr>
<td>
<textarea id="productId" placeholder="Product ID" style="resize: none; width: 100%;"></textarea>
</td>
<td>
<textarea id="title" placeholder="Title" style="resize: none; width: 100%;"></textarea></td>
<td>
<textarea id="startDate" placeholder="startdate" style="resize: none; width: 100%;"></textarea> </td>
</tr>
</thead>
</table>
Here are a couple things you might want to know:
I'm using the method querySelector() from document to select an element from the DOM by its class or id. Don't forget to add the # to . before the actual name.
Access the value of an element of type textarea with its property value.
No use of innerHTML += as it will force the browser to re-render all the content of #myTable even if you're just adding a row. Best way is to prepare an element as I do and append it to the table with appendChild().
To easily write HTML inside JavaScript code, you can use backticks `` and insert JS variables directly in the markup with the ${} syntax.

How to add and delete new row with new values each time using JavaScript?

I have been given a task to make 2 HTML pages, one with form where the user enter his/her contact information and another where the user's information are viewed in a table.
I just need to use these languages only (JavaScript, jquery, HTML, CSS ,bootstrap); no use of PHP/JSP, only client-side language
and no database should be used. Up until now I have done this much.
$(function()
{
$('#form').validate(
{
rules:
{
email:
{required:true,
email:true
},
gender:
{required:true
},
cont:{
required:true,
number:true}
}
})
});
function onsumit(){
localStorage.setItem("input0",1);
var ip=document.getElementById("name");
localStorage.setItem("input1", ip.value);
var ip2=document.getElementById("email");
localStorage.setItem("input2", ip2.value);
var ip3=document.getElementById("cont");
localStorage.setItem("input3", ip3.value);
var ip4=document.getElementById("gender");
localStorage.setItem("input4", ip4.value);
var ip5=document.getElementById("comment");
localStorage.setItem("input5", ip5.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a> CONTACT FORM</a>
<form class="table-responsive" id="form" name="form" action="next.html" method="get" onsubmit="onsumit()" >
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name"required>*<p id="p1"></p></td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont"required>*<p id="p2"></p></td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email"required>*<p id="p3"></p></td>
</tr>
<tr>
<td>Gender:</td>
<td><select id="gender" name="gender" required>
<option value="" >SELECT</option>
<option value="male">MALE</option>
<option value="female">FEMALE</option>
</select>*<p id="p4"></p></td>
</tr>
<tr>
<td>comments:</td>
<td> <textarea class="form-control" rows="5" id="comment" maxlength="100"></textarea>
</td>
</tr>
</table>
<label><input id="submit" type="submit" value="SUBMIT"></label>
</form>
</div>
now this is the second html page.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
body {
font: 20px Montserrat, sans-serif;
line-height: 1.8;
color: black;
}
p {font-size: 16px;}
.margin {margin-bottom: 45px;}
.bg-1 {
background-color: #1abc9c; /* Green */
color: #ffffff;
}
.bg-2 {
background-color: #474e5d; /* Dark Blue */
color: #ffffff;
}
.bg-3 {
background-color: #ffffff; /* White */
color: #555555;
}
.bg-4 {
background-color: #2f2f2f; /* Black Gray */
color: #fff;
}
.container-fluid {
padding-top: 70px;
padding-bottom: 70px;
}
.navbar {
padding-top: 15px;
padding-bottom: 15px;
border: 0;
border-radius: 0;
margin-bottom: 0;
font-size: 12px;
letter-spacing: 5px;
}
.navbar-nav li a:hover {
color: #1abc9c !important;
}
#divmid {
margin:20px;
padding:20px;
border:3px solid red;
}
table{
text-align:left ;
}
th, td {
padding: 20px;
text-align:left;
}
textarea{
max-height:300px;
resize:none;
}
#div1{
text-align:center;
}
#tab2 {
text-align:left ;
border:2px solid red;
margin-left:auto;
margin-top:40px;
margin-bottom:200px;
}
#pick{
padding:100px;
}
<style>
table, td,th{
border: 1px solid black;
}
</style>
<body onload="load()">
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>S No.</th>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>COMMENTS</th>
<th>EDIT</th>
</tr>
</table>
</div>
</body>
The problem is I need to create a row in second page each time a user input with the new values in the form, but what in have done, it only creating one row and always updating it with the new values. Though I have used Local storage but still I am stuck here.
The problem is in the line 6 of your code. The parameter 1 passed to the insertRow function instantiates the variable row with the first row of your table. This way, every time you use insertCell in the row variable it updates the value on this first row. I think switching to rowCount + 1 will do the job.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(rowCount + 1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
take a look at this code. I think it should be what you are looking for.
Everytime the form is submitted, I first get the value of the local storage and add the new entry as JSON.
On the other page, I get the local storage, transform the value to get an object from the JSON string and use that object to show the informations inside the table.
Hope this help!
First Page :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function onsumit() {
if (typeof(Storage) !== "undefined") {
// Exemple of str : {'d' : [{'name':'Mister A','cont':'1',email':'MisterA#test.com'},{'name':'Mister B','cont':'1','email':'MisterB#test.com'}]}
var str = localStorage.getItem("contactinformation");
var contactModel;
if (str !== '') {
contactModel = JSON.parse(str);
} else {
contactModel = {
d : []
};
}
contactModel.d[contactModel.d.length] = {
name:$('#name').val(),
cont:$('#cont').val(),
email:$('#email').val()
}
localStorage.setItem("contactinformation",JSON.stringify(contactModel));
return true;
} else {
// Sorry! No Web Storage support..
return false;
}
}
</script>
</head>
<body>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a>CONTACT FORM</a>
<form id="form" name="form" action="next.html" method="get" onsubmit="return onsumit();">
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name">*</td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont">*</td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email">*</td>
</tr>
</table>
<input id="submit" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
Second Page :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, td,th{
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
var str = localStorage.getItem("contactinformation");
var info = JSON.parse(str);
if (typeof(info.d) !== "undefined") {
for (var x=0;x<info.d.length;x++) {
$('#tab2').append('<tr><td>' + info.d[x].name + '</td><td>' + info.d[x].cont + '</td><td>' + info.d[x].email + '</td></tr>');
}
}
}
});
</script>
</body>
</html>

jQuery Dynamic form input validation

This question is based off of another StackOverflow question found here.
My goal is to build simple validation that ensures input fields are filled in sequential order based on their index (natural flow).
» The main complexity is that I'm trying to consolidate validation across different types of input.
» Specifically, radio button groups should be validated as one entity. When using the .prev() and .next() methods, the gender radio group should move to essay or age respectively, not male or female.
» The next bug is that I cannot get the age row to properly disable if the content in any previous row is undone/removed. It does not work consistently and I cannot figure out why.
» The validate button should make items that are filled in green, otherwise highlight them in red color.
If there is a more refined approach to this please feel free to elaborate. If there are easier selectors that I could be utilizes to build up the arrays for more streamlined manipulation and validation, please also enlighten me and share.
Almost Working Example
//StackOverflow Question - https://stackoverflow.com/q/37618826/5076162 [06-03-2016]
//Step 1: Declare the collection of all inputs that should be manipulated.
var $inputFields = $('textarea, input[type="text"], input[type="number"], input[type="radio"]');
//Step 2: Insert the collection into a single array using the .push() method.
var arr = [];
$inputFields.each(function() {
arr.push($(this));
});
//Step 3: Iterate through the newly created array and perform certain functions.
//Source - https://stackoverflow.com/a/5437904/5076162
$.each(arr, function(i) {
if (i > 0) {
$(this).attr('readonly', 'readonly').addClass('disabled');
$(':radio[readonly]:not(:checked)').attr('disabled', true);
//console.log("Iteration number: " + i);
}
});
var $justRadio = $('input[type="radio"]:disabled');
//Step 4: Detect input and apply logic for each situation. Note that different input types require different syntax.
$inputFields.on("propertychange input change focus blur", function(i) {
var index = $inputFields.index(this);
var next = $inputFields.eq(index + 1);
var $checkedRadio = $('input[type="radio"]:checked').length;
var radioCounter = $justRadio.length;
if ($(this).val() === "") {
$inputFields.filter(function() {
return $inputFields.index(this) > index;
}).attr("readonly", true).attr('disabled', true).addClass('disabled');
//console.log('disable Fired');
} else {
next.attr("readonly", false).attr('disabled', false).removeClass('disabled');
$justRadio = $('input[type="radio"]:disabled');
//console.log(radioCounter);
if (radioCounter < 2) {
$justRadio.closest('tr').find($justRadio).attr("readonly", false).attr('disabled', false).removeClass('disabled');
}
}
if ($checkedRadio > 0 && $justRadio.length === 0) {
$inputFields.last().attr("readonly", false).attr('disabled', false).removeClass('disabled');
//console.log("This fired: lastRow");
}
//Step 5: Implement a user interface button so they know they have filled in all fields.
var emptyCount = 0;
$inputFields.not($('input[type="radio"]')).each(function() {
if ($(this).val() === "") {
emptyCount = +1;
}
//console.log("Empty Count: " + emptyCount);
});
var vRCount = 0;
$inputFields.not($('input[type="text"], input[type="number"], textarea')).each(function() {
if ($(this).is(":checked")) {
vRCount = +1;
}
//console.log("Empty Count: " + emptyCount);
});
$('input.validateCheck').on("click", function() {
if (emptyCount === 0 && vRCount > 0) {
$inputFields.closest('tr').find('td').css("color", "green");
$('input.validateCheck').text("Success!").attr("value", "Success!");
}
});
});
table {
border-collapse: collapse;
}
td {
vertical-align: top;
border: solid 1px #ACE;
padding: 2px;
font-family: arial;
}
input {
width: 450px;
text-align: center;
}
textarea {
margin: 0;
width: 448px;
text-align: left;
}
input[type="radio"] {
width: 15px;
}
div.gender {
display: inline-block;
clear: none;
width: 219px;
}
.disabled {
background-color: #f1f1f1;
}
input[type="button"] {
width: 546px;
margin-top: 5px;
color: #FFF;
background-color: red;
border: solid 1px #ACE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form>
<table>
<tr>
<td>First name:</td>
<td>
<input type="text" name="firstname">
</td>
</tr>
<tr>
<td>Last name:</td>
<td>
<input type="text" name="lastname">
</td>
</tr>
<tr>
<td>Essay:</td>
<td>
<textarea rows="4" cols=""></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<div class='gender'>
<input type="radio" name="gender" value="male">Male</div>
<div class='gender'>
<input type="radio" name="gender" value="female">Female</div>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" name="age" min="18" max="99">
</td>
</tr>
</table>
<input class='validateCheck' type="button" value="Validate" />
</form>
Use HTML5 form validations. It is a lot easier and faster. Hope this helps...
<style>
form{font-size:100%;min-width:560px;max-width:620px;width:590px;margin:0 auto;padding:0}
form fieldset{clear:both;font-size:100%;border-color:#000;border-style:solid none none;border-width:1px 0 0;margin:0;padding:10px}
form fieldset legend{font-size:150%;font-weight:400;color:#000;margin:0;padding:0 5px}
label{font-size:100%}
label u{font-style:normal;text-decoration:underline}
input,select,textarea{font-family:Tahoma, Arial, sans-serif;font-size:100%;color:#000}
input:required ,select:required, textarea:required, radio:required{
font-family:Tahoma, Arial, sans-serif;
font-size:100%;
color:#000;
border-color:red;
background: #fff url(images/red-asterisk.png) no-repeat 98% center;
}
input:focus ,select:focus, textarea:focus, radio:focus{
background: #fff url(invalid.png) no-repeat 98% center;
box-shadow: 0 0 5px #d45252;
border-color: #b03535
}
input:valid ,select:valid, textarea:valid, radio:valid{
background: #fff url(valid.png) no-repeat 98% center;
box-shadow: 0 0 5px #5cd053;
border-color: #28921f;
}
:valid {box-shadow: 0 0 5px green}
:-moz-submit-invalid {box-shadow: 0 0 5px pink}
</style>
<form>
<table>
<tr>
<td>First name:</td>
<td>
<input type="text" id="firstname" name="firstname" required>
</td>
</tr>
<tr>
<td>Last name:</td>
<td>
<input type="text" name="lastname" required>
</td>
</tr>
<tr>
<td>Essay:</td>
<td>
<textarea rows="4" cols="20" required></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<div class='gender'>
<input type="radio" name="gender" value="male" required> Male</div>
<div class='gender'>
<input type="radio" name="gender" value="female" required> Female</div>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" name="age" min="18" max="99" required>
</td>
</tr>
</table>
<input class='validateCheck' type="submit" value="Validate" />
</form>

Categories

Resources