I have this code:
function buscar() {
var input, filter, table, tr, td, i;
input = document.getElementById("searchinput");
filter = accent_fold(input.value).toUpperCase();
table = document.getElementById("CSVTable");
tr = table.getElementsByTagName("tr");
var matching = false;
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[3];
if (td) {
if (accent_fold(td.innerHTML).toUpperCase().indexOf(filter) > -1) {
matching = true;
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
if (matching) {
$('#CSVTable').css('display', 'block');
$('#no-results').css('display', 'none');
} else {
$('#CSVTable').css('display', 'none');
$('#no-results').css('display', 'block');
}
}
Linked with this
<div id="buscador">
<input type="text" id="searchinput" onsearch="buscar()" placeholder="Cercar per cognom"/>
<span class="buscador-btn">
<button class="btns" type="submit" id="searchbutton" onclick="buscar(); showDiv();">
<span style="font-size: 15px; color: White;">
<i class="fa fa-search"></i>
</span><b>Cercar</b>
</button>
<button class="btnc" onclick="document.getElementById('searchinput').value = '' ; hideDiv();">
<span style="font-size: 15px; color: Red;">
<i class="fa fa-times"></i>
</span><b>Esborrar</b>
</button>
</span>
</div>
How to implement a script that, if, when click on search button and the searchinput is empty change its own placeholder=""
to warn that there is no text introduced to search? If not, continue with the script to search.
Thanks
CODE UPDATED TO THIS. Working but the return false don't stop the script:
var input = document.getElementById("searchinput"); if(input.value.trim().length){
var input, filter, table, tr, td, i;
input = document.getElementById("searchinput");
filter = accent_fold(input.value).toUpperCase();
table = document.getElementById("CSVTable");
tr = table.getElementsByTagName("tr");
var matching = false;
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[3];
if (td) {
if (accent_fold(td.innerHTML).toUpperCase().indexOf(filter) > -1) {
matching = true;
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
if (matching) {
$('#CSVTable').css('display', 'block');
$('#no-results').css('display', 'none');
} else {
$('#CSVTable').css('display', 'none');
$('#no-results').css('display', 'block');
}
}else{
input.placeholder="vacío";
return false;
}
}
There are many ways to go about this. One way can be by validating the input field when the form is submitted. This seems to be what you were going for.
The approach I used, is to place the <input>
field inside a <form>
element and call a function checkForm
to verify it's not empty, if it's not empty you can call your buscar
function there.