Search table by index (choose the index) - javascript

I have created a table where the user should be able to search by name or city.
When searching through names, the function should choose the correct table and the index attached to the call. Here is my attempt.
Desired Outcome: user chooses to search by name or by city and when he/she
types in the selected input, the function listens to the index number
that is in the call inside the input.
function searchIndex(id, index) {
// Declare variables
var filter, tr, td, i;
var table = document.getElementById(id);
var input = document.getElementById(index);
filter = input.value.toUpperCase();
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[''];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
const searchName = document.getElementById('searchName');
const searchCity = document.getElementById('searchCity');
const Select = document.getElementById('Select');
Select.addEventListener('click', () => {
if (Select.value == 'name') {
searchName.style.display = 'block';
searchCity.style.display = 'none';
} else {
searchName.style.display = 'none';
searchCity.style.display = 'block';
}
})
table {
margin: 0 auto;
text-align: center;
width: 500px;
}
td {
width: 250px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<div id="ListDiv">
<div class="Btns">
<input id="searchName" onkeyup="searchIndex('List' , [0])" type="text" placeholder="search name" />
<input id="searchCity" onkeyup="searchIndex('List' , [1])" style="display: none;" type="text" placeholder="search city" />
<div id="SelectDiv">
<select id="Select">
<option value="name">search name</option>
<option value="city">search city</option>
</select>
</div>
</div>
<table id="ListTop">
<tr>
<td>name</td>
<td>city</td>
</tr>
</table>
<div class="custScroll">
<table id="List">
<tr>
<td>hanna</td>
<td>big sandy</td>
</tr>
<tr>
<td>bonne</td>
<td>big sandy</td>
</tr>
<tr>
<td>thomas</td>
<td>big sandy</td>
</tr>
</table>
</div>
</div>

figured it out, changed the index from [0] to [index] and added [index] into function parameter list.
function searchIndex(id, id2, [index]) {
// Declare variables
var filter, tr, td, i;
var table = document.getElementById(id);
var input = document.getElementById(id2);
filter = input.value.toUpperCase();
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[index];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
const searchName = document.getElementById('searchName');
const searchCity = document.getElementById('searchCity');
const Select = document.getElementById('Select');
Select.addEventListener('click', () => {
if (Select.value == 'name') {
searchName.style.display = 'block';
searchCity.style.display = 'none';
} else {
searchName.style.display = 'none';
searchCity.style.display = 'block';
}
})
table {
margin: 0 auto;
text-align: center;
width: 500px;
}
td {
width: 250px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<div id="ListDiv">
<div class="Btns">
<input id="searchName" onkeyup="searchIndex('List' , 'searchName', [0])" type="text" placeholder="search name" />
<input id="searchCity" onkeyup="searchIndex('List' , 'searchCity', [1])" style="display: none;" type="text" placeholder="search city" />
<div id="SelectDiv">
<select id="Select">
<option value="name">search name</option>
<option value="city">search city</option>
</select>
</div>
</div>
<table id="ListTop">
<tr>
<td>name</td>
<td>city</td>
</tr>
</table>
<div class="custScroll">
<table id="List">
<tr>
<td>hanna</td>
<td>big sandy</td>
</tr>
<tr>
<td>bonne</td>
<td>hawkins</td>
</tr>
<tr>
<td>thomas</td>
<td>gilmer</td>
</tr>
</table>
</div>
</div>

Related

Give same result for "Home page" and "Homepage" in search table

This is an search table and working perfectly. But i want that on writing "home page" like this and "Homepage" like this. In both the cases it shows the result for Home Page. Similary for "About us" and
"Contact us".
The code is given below.
Pls can anyone help me
#myInput {
padding: 12px 20px 12px 40px;
border: 5px solid #ddd;
margin-bottom: 12px;
border-radius:20px;
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Search your product here">
<table id="myTable" align="center" border="5" width>
<tr class="header">
<th>Header 1 </th>
<th>Header 2</th>
</tr>
<tr>
<td><center>
<br><b>Home page</b></a></center></td>
<td> </td>
</tr>
<tr>
<td><center>
<br><b>About us</b></a></center></td>
<td>
</td>
</tr>
<tr>
<td><center>
<br><b>Contact us</b></a></center></td>
<td>
</td>
</tr>
</table>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
Use Regex to replace the whitespace
filter = filter.replace(/\s/g, '')
EDIT for comment
filter = filter.replace(/\s/g,'')
txtValue = txtValue.replace(/\s/g, '')
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
Remove all space using a regex pattern
let str = "Hello World !";
let spacesRemoved = str.replace(/ /g, "");
console.log(spacesRemoved);

Button search or filter

I have textbox and button here. But when I'm searching the data, data not available.
HTML
<input type="text" class="search" placeholder="Item Name"/>
<input type="submit" id="btnSearch" class="button" value="Search"/>
JavaScript
$('#btnSearch').click(function(e){
var grid = $('#grid').data('kendoGrid');
var field = 'itemName';
var operator = 'contains';
var value = this.value;
grid.dataSource.filter({
field: field,
operator: operator,
value: value
});
});
Here you can find full example of search and ready design using bootstrap
HTML
<div class="container">
<h3>The columns titles are merged with the filters inputs thanks to the placeholders attributes</h3>
<hr>
<p>Inspired by this snippet</p>
<div class="row">
<div class="panel panel-primary filterable">
<div class="panel-heading">
<h3 class="panel-title">Users</h3>
<div class="pull-right">
<button class="btn btn-default btn-xs btn-filter"><span class="glyphicon glyphicon-filter"></span> Filter</button>
</div>
</div>
<table class="table">
<thead>
<tr class="filters">
<th><input type="text" class="form-control" placeholder="#" disabled></th>
<th><input type="text" class="form-control" placeholder="First Name" disabled></th>
<th><input type="text" class="form-control" placeholder="Last Name" disabled></th>
<th><input type="text" class="form-control" placeholder="Username" disabled></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
CSS
.filterable {
margin-top: 15px;
}
.filterable .panel-heading .pull-right {
margin-top: -20px;
}
.filterable .filters input[disabled] {
background-color: transparent;
border: none;
cursor: auto;
box-shadow: none;
padding: 0;
height: auto;
}
.filterable .filters input[disabled]::-webkit-input-placeholder {
color: #333;
}
.filterable .filters input[disabled]::-moz-placeholder {
color: #333;
}
.filterable .filters input[disabled]:-ms-input-placeholder {
color: #333;
}
Javascript
$(document).ready(function(){
$('.filterable .btn-filter').click(function(){
var $panel = $(this).parents('.filterable'),
$filters = $panel.find('.filters input'),
$tbody = $panel.find('.table tbody');
if ($filters.prop('disabled') == true) {
$filters.prop('disabled', false);
$filters.first().focus();
} else {
$filters.val('').prop('disabled', true);
$tbody.find('.no-result').remove();
$tbody.find('tr').show();
}
});
$('.filterable .filters input').keyup(function(e){
/* Ignore tab key */
var code = e.keyCode || e.which;
if (code == '9') return;
/* Useful DOM data and selectors */
var $input = $(this),
inputContent = $input.val().toLowerCase(),
$panel = $input.parents('.filterable'),
column = $panel.find('.filters th').index($input.parents('th')),
$table = $panel.find('.table'),
$rows = $table.find('tbody tr');
/* Dirtiest filter function ever ;) */
var $filteredRows = $rows.filter(function(){
var value = $(this).find('td').eq(column).text().toLowerCase();
return value.indexOf(inputContent) === -1;
});
/* Clean previous no-result if exist */
$table.find('tbody .no-result').remove();
/* Show all rows, hide filtered ones (never do that outside of a demo ! xD) */
$rows.show();
$filteredRows.hide();
/* Prepend no-result row if all rows are filtered */
if ($filteredRows.length === $rows.length) {
$table.find('tbody').prepend($('<tr class="no-result text-center"><td colspan="'+ $table.find('.filters th').length +'">No result found</td></tr>'));
}
});
});
I think this will help you..!
$('.searchBtn').click(function() {
var title = $('#title').val(); //value from search input box
$('.pubTitle').each(function() { //searches each container
var str = $(this).text(); //finds just the title text
if (str.indexOf(title) > -1) { //compares search text to title text
$(this).show(); // if the entry is found show the container
} else {
$(this).hide(); // if not found, hide it.
}
});
});
$("#search").keyup(function(){
_this = this;
// Show only matching TR, hide rest of them
$.each($("#turnoverTaxTbl tbody tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) === -1)
$(this).hide();
else
$(this).show();
});});
The filter methods return a new array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var filter_data = grid.dataSource.filter(item =>
(
item.field == field && item.opertor && operator && item.value == value)
);
console.log(".......filter_data......", filter_data)
now you can use this new filter_data

Cannot read property 'childNodes' checkbox to get value from same row

Below code should get me the value of the column next to the checked box in the table, but, once the button is clicked, I am getting:
Cannot read property childNodes of null
Note: database from firebase which where the values from the table come from
Table image :
rootRefReAgents.on("child_added", snap => {
var AgentName = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentName + "</td><td><INPUT TYPE=\"Checkbox\"> </Input></td></tr>");
});
}
function ActionData(){
let agents = [];
let table = document.getElementById("table_body_Test");
let childNodes = Array.from(table.childNodes);
// let childNodes = table.childNodes;
for (let child of childNodes.values()) {
console.log(`child: ${child}`);
if (child.constructor.name !== "HTMLTableRowElement") {
continue;
}
let agent = child.childNodes.item(1).innerHTML;
console.log(`agent: ${agent}`);
let checkbox = child.childNodes.item(3).childNodes.item(1);
console.log(`checkbox: ${checkbox}`);
console.log(checkbox.checked);
if (checkbox.checked) {
agents.push(agent);
}
}
console.log(`agents: ${agents}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
<button id="submitBtn" onclick="ActionData()">Next</button>
ES6 brought new methods that simplify the code and its reading
const tableBody = document.querySelector('#testTable tbody' );
document.querySelector('#submitBtn').onclick=()=>
{
let agents = [];
console.clear();
for (let rowX of tableBody.rows )
{
let
agent = rowX.cells[0].textContent,
checkbox = rowX.cells[1].querySelector('input[type=checkbox]')
;
console.log( 'agent:', agent, 'checked:', checkbox.checked);
if (checkbox.checked) { agents.push(agent); }
}
console.log( 'agents (array):', agents.join(' / '));
}
/// bonus info :
/*
rootRefReAgents.on("child_added", snap=>{
let
newRow = tableBody.insertRow(-1);
newRow.insertCell(0).textContent = snap.child("Name").val();
newRow.insertCell(1).innerHTML = '<input type="Checkbox">';
});
*/
#testTable { margin: auto; border-collapse: collapse }
#testTable thead tr {
color: #D2002E;
background: #FFCC01;
height:32px;
font-weight: bold;
}
#testTable tr:nth-child(even) {background-color: lightgrey }
#testTable td { border:1px solid grey; padding: 0 20px; }
#testTable td:nth-child(2) { text-align: center }
<table id="testTable">
<thead>
<tr> <td>Agents</td> <td>Select</td> </tr>
</thead>
<tbody>
<tr> <td>AMC</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>Mygulfex</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>topStar</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>WMC</td> <td> <input type="checkbox" > </td> </tr>
</tbody>
</table>
<button id="submitBtn" >see Selects in console</button>

Add another search field in function

I have a function that works perfectly
But the need arose, to add another field to the research, I do not know how to solve. It has a checkbox in the form, if it is filled, it fetches the data true in the table, if not the data false, how to add in the code below? I'm in doubt, if at all possible.
function myFunction2() {
var input, filter, table, tr, td, i, filtro;
input = document.getElementById("busca2");
filter = input.value.toUpperCase();
table = document.getElementById("tablepesquisa2");
tr = table.getElementsByTagName("tr");
filtro = document.getElementById("filtroPesquisa2").value;
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[filtro];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
<div class="form-group">
<div class="col-sm-3">
<select id="filtroPesquisa2" class="form-control">
<option value="0">Código</option>
<option value="1">Descrição</option>
</select>
</div>
<div class="col-sm-7">
<input type="text" id="busca2" placeholder="Pesquisa.." onkeyup="myFunction2();" class="form-control" />
</div>
</div>
<div class="modal-body">
<div class="table-overflow col-sm-12">
<table class="table table-responsive table-hover" id="tablepesquisa2">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Produto) {
<tr>
<td>#item.Codigo</td>
<td>#item.nome</td>
<td align="right">
<i class="fa fa-check-circle fa-lg"></i>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="col-sm-3" style="text-align:left;">
<input type="checkbox" asp-for="Produtos" name="Produtos" id="Produtos"/>
<label asp-for="Produtos" class="control-label"></label>
<span asp-validation-for="Produtos" class="text-danger"></span>
</div>
<div class="col-sm-3" style="text-align:left;">
<input type="checkbox" asp-for="Servico" name="Servico" id="Servico"/>
<label asp-for="Servico" class="control-label"></label>
<span asp-validation-for="Servico" class="text-danger"></span>
</div>
In this table, have these two fields, then need to be filtered if they are marked or not, if product is marked, have to bring only the fields where product = true, and if it is the other, only the fields that the other is true
EDIT
I managed to solve, just by selecting the correct column and comparing to true
I solved the problem by doing this way:
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[filtro];
td1 = tr[i].getElementsByTagName("td")[4];
td2 = tr[i].getElementsByTagName("td")[3];
var tbBoolean = ($(td2).text() == "True" ? true : false);
if ($('#Venda').prop("checked") == true) {
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1 && $(td1).text() == idEmpresa || $(td1).text() == "") {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
else {
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1 && tbBoolean == false) {
if ($(td1).text() == idEmpresa || $(td1).text() == "") {
tr[i].style.display = "";
}
} else {
tr[i].style.display = "none";
}
}
}
}

How to check the table whether the same roll number exists or not using javascript

Can we can check the roll number already exists or not.
with javascript
can we validate this
Showing with a alert message that the roll number exists if it is
already in the table
.
window.onload = function() {
document.getElementById('new').style.display = 'none';
};
function addtable(){
document.getElementById('new').style.display = 'block';
Rollno = document.getElementById("roll_number");
Name = document.getElementById("student_name");
Class = document.getElementById("class");
var Gender = null;
var inputElements = document.getElementsByClassName('gender');
for (var i = 0; inputElements[i]; ++i) {
if(inputElements[i].checked){
Gender = inputElements[i].value;
break;
}
};
Age = document.getElementById("age");
Phone = document.getElementById("phone_number");
var Result = null;
var inputElements = document.getElementsByClassName('result');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
Result = inputElements[i].value;
break;
}
};
var table = document.getElementById("new");
rowCount = table.rows.length;
row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= Rollno.value;
row.insertCell(1).innerHTML= Name.value;
row.insertCell(2).innerHTML= Class.value;
row.insertCell(3).innerHTML= Gender;
row.insertCell(4).innerHTML= Age.value;
row.insertCell(5).innerHTML= Phone.value;
row.insertCell(6).innerHTML= Result;
row.insertCell(7).innerHTML='<input type="submit" value = "Delete" onclick="deleteRow(this)">';
var roll = document.forms["student_detail"]["roll_number"].value;
if (roll == "") {
alert("Rollno must be filled out");
return false;
}
var name = document.forms["student_detail"]["student_name"].value;
if (name == ""){
alert("Name must be filled out");
return false;
}
var clas = document.forms["student_detail"]["class"].value;
if (clas == "") {
alert("select the class");
return false;
}
var age = document.forms["student_detail"]["age"].value;
if (age == ""){
alert("Age must be filled out");
return false;
}
var phone = document.forms["student_detail"]["phone_number"].value;
if (phone == "") {
alert("Phone number must be filled out");
return false;
}
if (document.student_detail.result1.checked == true && document.student_detail.result2.checked == true){
alert('Select any one result');
return false ;
}
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("new");
table.deleteRow(index);
}
function myFunction() {
var x = document.getElementById('myTable');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var change = document.getElementById("toggle");
if (change.innerHTML === "Hide Form")
{
change.innerHTML = "Show Form";
}
else {
change.innerHTML = "Hide Form";
}
}
function hideElem(){
document.getElementById('new').style.visibility = "hidden";
}
function showElem(){
document.getElementById('new').style.visibility = "visible";
}
.abc table{
width: 100%;
border-collapse: collapse;
}
.abc table th{
border: 1px solid #000;
}
.abc table td{
border: 1px solid #000;
}
h2{
color: black;
text-shadow: 2px 2px 8px #FF0000
}
input[type=text],select,input[type=number]{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 2px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=button] {
width: 50%;
background-color: #4CAF50;
color: white;
padding: 14px 10px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=button]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<form name="student_detail" method="post" action="#" onsubmit="return addtable();">
<table id="myTable" >
<tr>
<td><h2>School Management Application</h2></td>
</tr>
<tr>
<td><label for="roll_number">Roll no</label></td>
<td><input type="text" id="roll_number" name="roll_number" placeholder="Roll Number"></td>
</tr>
<tr>
<td><label for="student_name">Student name</label></td>
<td><input type="text" id="student_name" name="student_name" placeholder="Student Name"></td>
</tr>
<tr>
<td><label for="class">Class</label></td>
<td><select name="class" id="class">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select></td>
</tr>
<tr>
<td><label>Gender</label></td>
<td><input type="radio" class="gender" name="gender" value="male">Male
<input type="radio" class="gender" name="gender" value="female">Female</td>
</tr>
<tr>
<td><label for="age">Age</label></td>
<td><input type="number" id="age" name="age" placeholder="Age"></td>
</tr>
<tr>
<td><label for="phone_number">Phone number</label></td>
<td><input type="text" id="phone_number" name="phone_number" placeholder="Phone Number"></td>
</tr>
<tr>
<td><label>Result</label></td>
<td><input type="checkbox" class="result" name="result1" value="passed" >Passed
<input type="checkbox" class="result" name="result2" value="failed" />Failed</td>
</tr>
<tr>
<td><input type="button" value="Submit" onclick="addtable()"></td>
</tr>
</table>
</form>
<table>
<tr>
<td><input type="button" value="Hide Form" id="toggle" onclick="myFunction()">
<input type="button" value="Hide table" id="tab" onclick="hideElem()">
<input type="button" value="Show table" id="tab1" onclick="showElem()"></td>
</tr>
</table>
<div class="abc">
<table id="new">
<tr>
<th>Rollno</th>
<th>Student name</th>
<th>Class</th>
<th>Gender</th>
<th>Age</th>
<th>Phone number</th>
<th>Result</th>
</tr>
</table>
</div>
Need to get alert if the same roll number enters again.After
submiting And a alert message to be shown
Can any one help me to do this
Here's a function that checks for duplicates
checkDupes($("#someId"));
function checkDupes(itemArray) {
var isdupe = false;
for (var i = itemArray.length - 1; i >= 0; i--) {
var value = itemArray[i].value;
if (value == null || value == '' || value.trim().length == 0) {
itemArray[i].style.backgroundColor = 'red';
} else {
if (i > 0) {
for (var j = i - 1; j > -1 && i > 0; j--) {
if (value.trim().toLowerCase() == itemArray[j].value.trim().toLowerCase()) {
itemArray[i].style.backgroundColor = 'red';
isdupe = true;
}
}
if (!isdupe) {
itemArray[i].style.backgroundColor = 'transparent';
}
}
}
}
}

Categories