I am in the process of creating a website and I have a HTML table that you can add a row to by clicking a button. There is an input box for every column in every row. When the table is submitted, it should retrieve all the info from all the input boxes and put it in an array that separates the rows.
I am positive that this requires a loop and I tried getting the children from the tbody element, but that didn't return the correct values.
function submitForm() {
var c = $("#tbl").children;
console.log(c);
}
it's very simple, just browse the rows of the array and the cells of each line.
So obviously I do not know what type of array you want, but I've made you here an example of a array with Jquery.
I hope it will help you.
$(function(){
var datas = [];
$.each($('#table tr'), function(index, val) {
var childs = $(this).children('td');
var array = {childs: []};
$.each(childs, function(i, v) {
//get your value
var value = $(this).text();
array.childs.push(value);
});
datas.push(array);
});
//final result
console.log(datas);
});
<!DOCTYPE html>
<html>
<head>
<title>Resultat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<table id="table" border="1">
<tr>
<td>Value1 line1</td>
<td>Value2 line1</td>
<td>Value3 line1</td>
</tr>
<tr>
<td>Value1 line2</td>
<td>Value2 line2</td>
<td>Value3 line2</td>
</tr>
<tr>
<td>Value1 line3</td>
<td>Value2 line3</td>
<td>Value3 line3</td>
</tr>
</table>
</div>
</body>
</html>
Here is a simplified solution you could easily work into your form submission code.
const tdInputs = document.querySelectorAll('td > input');
let inputValues = [];
tdInputs.forEach(input => inputValues.push(input.value));
console.log(inputValues);
<table>
<tr>
<td><input type="text" value="value1"></td>
</tr>
<tr>
<td><input type="text" value="value2"></td>
</tr>
</table>
http://jsfiddle.net/xpvt214o/1022151/
Assuming...
Since there's hardly any code in the question, I took the liberty to add what I consider necessary to which the question neglected to provide. If you don't have the setup like how my demo is setup, I recommend that you consider refactoring your code a little.
Setup
The demo is fully functional:
Adds and removes rows
A <form> is wrapped around the <table> since there's an <input> in each <td>
The <form> will send its data to a live test server when the submit event is triggered.
The live server will send a response as a JSON which will be displayed in the <iframe> located below the <table>.
This default behavior triggered by asubmit event will be temporarily postponed by this function:
// Earlier in the code, this was called to interrupt the default behavior
event.preventDefault();
...
/* .map() all inputs in the table...
| store all the strings that contain an input's name and value into a jQuery Object
| .get() the data from the jQuery Object as an array
| although optional, you can present it as a string by using `.join()`
*/// Finally, submit the form data to the test server
var dataArray = $('.data input').map(function(idx, txt) {
return `${$(this).attr('name')}: ${$(this).val()}`;
}).get().join(', ');
console.log(JSON.stringify(dataArray));
$('.ui').submit();
/**/
Demo
var count = 0;
var row = `<tr><td><input name='a'></td><td><input name='b'></td><td><input name='c'></td><td><button class='del' type='button'>➖</button></td></tr>`;
$('.ui').on('click', 'button', function(e) {
e.preventDefault();
if ($(this).hasClass('add')) {
count++;
$('.data').append(row);
$('tr:last input').each(function() {
var name = $(this).attr('name');
$(this).attr('name', name+count);
});
} else if ($(this).hasClass('del')) {
$(this).closest('tr').remove();
} else {
var dataArray = $('.data input').map(function(idx, txt) {
return `${$(this).attr('name')}: ${$(this).val()}`;
}).get().join(', ');
console.log(JSON.stringify(dataArray));
$('.ui').submit();
}
});
.ui {width: 100%}
.set {padding: 0;}
.data {width: 100%; table-layout: fixed; border: 1px ridge #777; border-spacing: 1px}
td {width: 30%; padding: 0 1px}
tr td:last-of-type {width: 10%}
.add {margin: 0 0 0 85%;}
iframe {width: 100%}
.as-console-wrapper.as-console-wrapper {
max-height: 20%;
}
.as-console-row.as-console-row::after {
content:'';
padding:0;
margin:0;
border:0;
width:0;
}
<form class='ui' action='https://httpbin.org/post' method='post' target='response'>
<fieldset class='set'>
<button class='add' type='button'>➕</button>
<button>🡺</button>
</fieldset>
<table class='data'>
<tr><td><input name='a0'></td><td><input name='b0'></td><td><input name='c0'></td><td><button class='del' type='button'>➖</button></td></tr>
</table>
</form>
<iframe src='about:blank' name='response'></iframe>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I have a table which is hidden which contains 1272 rows and within it 3 columns with a
Store Name
Postcode
Button
The script is meant to search for all td cells for either a store name or a postcode and is not returning the desired results.
This is a link to the search
Advice appreciated
$("#searchterm").on("keyup", function() {
var value = $.trim($(this).val().toLowerCase());
$("table#participating_stores tr:gt(0)").each(function(index) {
if (index !== 0) {
$row = $(this);
var $tdElement = $row.find("td");
var id = $.trim($tdElement.text().toLowerCase())
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
//highlight matching text, passing element and matched text
$row.show();
}
}
});
});
I think this is what you are looking for. I've made this runnable snippet which hopefully makes things more clear for you and anyone else trying to think about this problem.
$("#searchterm").on("keyup", function() {
var value = $(this).val();
$("table tr:not(:first)").show().filter(function(index) {
return $(this).find("td").text().indexOf(value) == -1;
}).hide();
});
table, tr, td, th{
border: 1px solid black;
padding: 3px;
}
table th{
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr><th>Postal Code</th><th>Store Name</th></tr>
<tr><td>12345</td><td>store name</td></tr>
<tr><td>99999</td><td>another store name</td></tr>
<tr><td>54321</td><td>yet another name</td></tr>
<tr><td>34343</td><td>4th name</td></tr>
<tr><td>87898</td><td>fifth name</td></tr>
</table>
<br />
<input type="text" id="searchterm" placeholder="search"></input>
I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. I need to type in this below format in the textbox.
Name=Value
This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox. let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as
Hello=World
And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.
Hello=World
ABC=PQR
But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format. Names and Values can contain only alpha-numeric characters. I also have three more buttons Sort by name, Sort by value and Delete button. Once I click either of these buttons, then it should sort entries in TextArea list using either name or value and delete entries as well. Now I have all above things working fine without any issues.
Here is my jsfiddle. I need to use plain HTML, CSS and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning. Now I am trying to see whether we can make UI more responsive like the UI should adjust based on what screen size is viewing it. For example, if viewed on a mobile phone (i.e. Android or iPhone), the page should automatically adjust to present the layout in a better way. This also applies to re-sizing the browser on desktop, and viewing the page on a tablet.
What are the changes I need to make in my CSS or HTML to make it more responsive? Any improvements I can make here? Since my UI is very simple so there should be some easy way or some improvements I can make here.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
.main{
background:white;
padding: 35px;
border-radius: 5px;
}
#my-text-box {
font-size: 18px;
height: 1.5em;
width: 585px;
}
#list{
width:585px;
height:300px;
font-size: 18px;
}
.form-section{
overflow:hidden;
width:700px;
}
.fleft{float:left}
.fright{float:left; padding-left:15px;}
.fright button{display:block; margin-bottom:10px;}
html, body {
height: 100%;
font-family: "Calibri";
font-size: 20px;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
background-color: #5C87B2;
}
</style>
<script language="javascript" type="text/javascript">
document.getElementById('add').onclick = addtext;
function addtext() {
var nameValue = document.getElementById('my-text-box').value;
if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue)){
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = nameValue;
x.add(option);
}
else
alert('Incorrect Name Value pair format.');
}
document.getElementById('btnDelete').onclick = deleteText;
function deleteText(){
var myList = document.getElementById('list');
var i;
for (i = myList.length - 1; i>=0; i--) {
if (myList.options[i].selected) {
myList.remove(i);
}
}
}
document.getElementById('sortByValue').onclick = sortByValue;
function sortByValue(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function(a, b){
if(a != "" && b != ""){
return a.split('=')[1].localeCompare(b.split('=')[1])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a != "" && b != ""){
return a.split('=')[0].localeCompare(b.split('=')[0])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
</script>
</head>
<body>
<div class = 'main'>
<h3>Test</h3>
<label for="pair">Type your text</label></br>
<div class="form-section">
<div class="fleft">
<input type='text' id='my-text-box' value="Name=Value" />
</div>
<div class="fright">
<button type="button" id='add' onclick='addtext()'>Add</button>
</div>
</div>
<label for="pairs">Name/Value Pair List</label></br>
<div class="form-section">
<div class="fleft">
<select id="list" multiple></select>
</div>
<div class="fright">
<button type="button" id='sortByName' onclick='sortByName()'>Sort by name</button>
<button type="button" id='sortByValue' onclick='sortByValue()'>Sort by value</button>
<button type="button" id='btnDelete' onclick='deleteText()'>Delete</button>
<button type="button">Show XML</button>
</div>
</div>
</div>
</body>
</html>
W3 have a number of resources on responsive web design:
http://www.w3schools.com/html/html_responsive.asp
http://www.w3schools.com/css/css_responsive_intro.asp
Without using PHP to detect the browser/user agent, your responsive design will typically involve ensuring the site is more fluid and flowing, allowing for changing browser widths (as in the first example above) and/or by delivering differing stylesheets depending on the viewport size and media type in CSS (second example).
I'm trying to implement a live search (filtering) feature with jQuery for a table. The table contains a list of people and their grad year and high school. When the user starts typing inside the search input, the table will start filtering out all the rows that do not contain the value of the search input. It will also add the class of highlight to the td that the searched text was in.
How can I filter each row and highlight the td element when the user searches something? I tried implementing this with the code below but to no avail. What can I tweak in this code to get this working correctly?
Below is my code. Here is my jsFiddle: http://jsfiddle.net/mikerodriguez/jybrnt22/2/
jQuery
$("#search").on("keyup", function(){
var input = $(this).val();
$("#search_table tbody tr").each(function(){
var row = $(this);
var td_element = $("#search_table tbody tr td");
if(input !== td_element.text()){
row.hide();
}else{
row.show();
td_element().addClass("highlight");
}
})
});
CSS
body {
margin: 0;
padding: 0;
font-family: Arial;
font-size: 14px;
}
.search_field {
padding: 15px;
}
.search_field input[type="text"] {
padding: 15px;
width: 98%;
font-size: 18px;
}
.search_table_container {
padding: 15px;
}
.search_table {
width: 100%;
}
.search_table th {
background-color: #AAA;
font-weight: bold;
padding: 10px 0px;
}
.search_table td {
text-align: center;
background-color: #CCC;
padding: 15px 0px;
}
HTML
<div class="search_field">
<input type="text" id="search" placeholder="Search for Person, Class, or High School">
</div>
<div class="search_table_container">
<table id="search_table" class="search_table">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>High School</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Smith</td>
<td>2014</td>
<td>Some High School</td>
</tr>
<tr>
<td>Homer Simpson</td>
<td>2015</td>
<td>Springfield High School</td>
</tr>
<tr>
<td>Bugs Bunny</td>
<td>2050</td>
<td>Looney Tunes High School</td>
</tr>
<tr>
<td>George Washington</td>
<td>1749</td>
<td>Georgetown Academy</td>
</tr>
<tr>
<td>Marty McFly</td>
<td>1991</td>
<td>Back to the Future</td>
</tr>
<tr>
<td>Doc Emmet Brown</td>
<td>1965</td>
<td>One Point Twenty-one Gigawatts</td>
</tr>
</tbody>
</table>
</div>
One problem is:
input !== td_element.text()
You're comparing partial input values to the entire contents of your columns. Instead it should be something like
td_element.text().indexOf(input) == -1
But there were actually quite a few issues (including simple syntax errors, e.g., td_element is not a function). I tweaked your example to something that works: http://jsfiddle.net/gh5kjku5/2/
$("#search").on("keyup", function(){
var input = $(this).val();
$("#search_table tbody tr").each(function(){
var row = $(this);
var td_elements = row.find('td');
var colText = td_elements.text();
if(colText.indexOf(input) == -1){
row.hide();
}else{
row.show();
td_elements.addClass("highlight");
}
})});
You'll need to do a bit more work to do things like reset the td background colors when the search box is cleared. Good luck!
hi try this it's working.
$("#search").on("keyup", function () {
var input = $(this).val();
if (input == '') {
$("#search_table tbody tr").show();
} else {
$("#search_table tbody tr").show();
$("#search_table tbody tr").each(function () {
var row = $(this);
var td_element = $("#search_table tbody tr td");
if ($(row).text().trim().toUpperCase().indexOf(input.toUpperCase()) > -1) {
row.hide();
} else {
row.show();
}
});
}
});
see jsfiddle link http://jsfiddle.net/jybrnt22/14/
I have a span which has a predefined value which is initiated on page load.
The user can alter the values by interacting with an input field.
My problem is that all the spans are in a table, and whenever the number is altered
instead of appearing in the exact same spot as the predefined number, it positions itself up like 20px or so.
Any help will be appreciated.
HTML
<table class="tbl1">
<tr>
<td style="overflow: hidden; width: 280px; text-align: left; valign: top"><span class="Cs boxGreen">A</span>
</td>
<td width="18%"><span class="number1Output"></span>
</td>
</tr>
</table>
JS
var currency = "£";
(function ($) {
$(window).load(function () {
$('.number1Output').html($('#number1').val());
});
});
function displayNumber(value, id, id2) {
var output = '.' + id + "Output";
if (value == 0) {
$(output).html('');
$(id2).html("free");
} else {
$(output).html('+' + value + currency + ' ');
$(id2).html(value + currency);
}
}
If you are changing the width of a span/field/window/etc. and the positioning does not look right you might want to use CSS. min-width can help with this.
Scenario:
I have a results table with a checkbox, when the checkbox is checked, the content of the row(actually 2 columns concateneted only, are copied to a new div, with the job code and job name). This works pretty well, and I am avoiding duplicated already.
However, in the new results div, I am creating an anchor tag to remove the div itself.
After the div has been removed, I should be able to add the selected job again with the checkbox.
Please note that there are many jobs in the results table, so putting the flag to false again will not work.
Also if you find a better title for this question, please let me know
//On every checkbow that is clicked
var flag = false;
$("#ctl00_PlaceHolderMain_myGrid input").change(function () {
if (this.checked && flag === false) {
flag = true;
var jobCode = $(this).parent().parent().parent().find("td:eq(2)").text()
var jobName = $(this).parent().parent().parent().find("td:eq(1)").text()
var displayvalue = jobCode.toUpperCase() + " - " + jobName.toUpperCase();
AddSelectedJob(jobCode, displayvalue);
//$(this).unbind('change'); //Unbind the change event so that it doesnt fire again
FillSelectedJobs();
}
});
//Add selected job in the results div
function AddSelectedJob(id, display) {
//create a div for every selected job
$("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + 'Remove selected job</div>');
}
//Removes the selected job from the resutls div
function removeSelectedJob(el) {
$(el).parent().remove();
}
The generated html is like this:
<div>
<div style="height: 300px; overflow: auto; float: left">
<div>
<table cellspacing="0" cellpadding="4" id="ctl00_PlaceHolderMain_myGrid" style="color:#333333;width:100%;border-collapse:collapse;">
<tr style="color:White;background-color:#5D7B9D;font-weight:bold;">
<th scope="col"> </th><th scope="col">JobCode</th><th scope="col">JobName</th><th scope="col">JobPartner</th><th scope="col">JobManager</th><th scope="col">ClientName</th>
</tr><tr style="color:#333333;background-color:#F7F6F3;">
<td>
<input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1" type="checkbox" name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1" />
</td><td>jobcode01</td><td>jobname</td><td>xx</td><td>xx</td><td>xx</td>
</tr>
</table>
</div>
</div>
<div style="margin-top: 0px; margin-left: 10px; float: left">
<span>Selected :</span>
<div id="ResultsDiv" style="margin-top: 0px">
</div>
</div>
Firstly I suggest some changes to your HTML. Separate out the styles from your DOM and place them in classes.
This makes sure there is separation of concerns
HTML
<div>
<div class="divMain">
<div>
<table cellspacing="0" cellpadding="4"
id="ctl00_PlaceHolderMain_myGrid" class="table">
<tr class="rowHead">
<th scope="col"> </th>
<th scope="col">JobCode</th>
<th scope="col">JobName</th>
<th scope="col">JobPartner</th>
<th scope="col">JobManager</th>
<th scope="col">ClientName</th>
</tr>
<tr class="row">
<td>
<input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1"
type="checkbox"
name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1"
data-flag="false" />
</td>
<td>column1</td>
<td>column2</td>
<td>column3</td>
<td>column4</td>
<td>column5</td>
</tr>
</table>
</div>
</div>
<div class="m0 selected">
<span>Selected :</span>
<div id="ResultsDiv" class="m0"></div>
</div>
CSS
.divMain{
height: 300px;
overflow: auto;
float: left
}
.table{
color:#333333;
width:100%;
border-collapse:collapse;
}
.rowHead{
color:White;
background-color:#5D7B9D;
font-weight:bold;
}
.row{
color:#333333;
background-color:#F7F6F3;
}
.m0{
margin-top: 0px;
}
.selected{
margin-left: 10px;
float: left
}
Javascript
$("#ctl00_PlaceHolderMain_myGrid input").change(function () {
// Next cache your selector
// so that you need not crawl the DOM multiple times
var $this = $(this),
$row = $this.closest('.row'),
currFlag = Boolean($this.data('flag'));
// As there might be multiple jobs , a single flag variable
// will not work. So you can set a data-flag attribute on the
// input that stores the current value
if (currFlag === false && this.checked) {
// Set the corresponding flag to true
$this.data('flag', true);
var jobCode = $row.find("td:eq(2)").text(),
jobName = $row.find("td:eq(1)").text(),
displayvalue = jobCode.toUpperCase() + " - "
+ jobName.toUpperCase(),
inputId = $this.attr('id')
// Pass the input name too as you need to set the value of
// the corresponding flag value again as you can add it multiple times
AddSelectedJob(jobCode, displayvalue, inputId);
FillSelectedJobs();
}
});
//Add selected job in the results div
function AddSelectedJob(id, display, inputId) {
//create a div for every selected job
// Use the inputId to save it as a data-id attribute
// on anchor so that you can set the value of the flag after
// removing it
var html = '<div class="selectedjobs" id=' + id + '>' + display ;
html += '<a href="javascript" data-id="'+ inputId
+'">Remove selected job</a></div>';
$('[id$=ResultsDiv]').append(html);
}
// Remove the inline click event for the anchor and delgate it to the
// static parent container
$('[id$=ResultsDiv]').on('click', 'a', function(e) {
var $this = $(this),
$currentCheckbox = $this.data('id');
// Set the flag value of the input back to false
$('#'+ $currentCheckbox).data('flag', false);
e.preventDefault(); // prevent the default action of the anchor
$this.closest('.selectedjobs').remove();
});
function FillSelectedJobs() {
//save values into the hidden field
var selectedJobs = $("[id$=ResultsDiv]").find("[class$='selectedjobs']");
var returnvalue = "";
for (var i = 0; i < selectedJobs.length; i++)
returnvalue += selectedJobs[i].id + ";";
$("[id$=HiddenClientCode]").val(returnvalue);
}
Check Fiddle