Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A js filter manipulating DOM (answer to an exercise)
console.log("Initializing mySearch");
var filter=document.getElementById('myfilter')
buildForm(filter, filterTable)
function filterTable(){
this.table.setAttribute('id', 'deu-certo')
var rows = this.table.querySelectorAll('tr+tr')
var fields = this.form.querySelectorAll('input')
for (var r=0; r<rows.length; r++){
if (matchFilter(rows[r], fields))
rows[r].classList.remove('hidden')
else
rows[r].classList.add('hidden')
}
}
function matchFilter(row, fields){
var columns = row.querySelectorAll('td')
for (var i=0; i<columns.length; i++){
var haystack = columns[i].innerText
var needle = fields[i].value
if (!haystack){
if (needle){
return false
}else{
continue
}
}
if (!haystack.match(needle)){
return false
}
}
return true
}
function buildForm(filter, action){
var tables = document.querySelectorAll('table')
// for now there is no need to make this work for multiple tables
var form = createFields(tables[0]);
var submit = document.createElement('button')
submit.setAttribute('type', 'button')
submit.addEventListener('click', action)
submit.innerHTML = 'filter the table'
submit.table = tables[0]
filter.appendChild(form)
form.appendChild(submit)
}
function createFields(t){
var form = document.createElement('form')
var fields = t.querySelectorAll('th')
fields.forEach((field)=>{createField(form,field)});
return form
}
function createField(form, field){
var newLabel = document.createElement('label')
newLabel.innerText = field.innerText
newLabel.setAttribute('for', field.innerText)
var newField = document.createElement('input')
newField.setAttribute('type', 'text')
newField.setAttribute('name', field.innerText)
newLabel.appendChild(newField)
form.appendChild(newLabel)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.