newbieprogrammer newbieprogrammer - 4 months ago 8
Javascript Question

Javascript doesnt work in html file

I have a working javascript in JS fiddle but when copied to html file it doesn't fully work. I have checked other post related to the same topic but no solution.
the filter is not working

https://jsfiddle.net/jpm50m0s/

Code in HTML

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script>
$(document).ready(function(){
var table = document.getElementById("table");
table.innerHTML = "";
for (var i = 0; i < 6; i++) {
var js = "apple";
var tr = document.createElement("tr");
var td = document.createElement("td");

td.innerHTML = js + i ;
tr.appendChild(td);
table.appendChild(tr);
}}

$(function() {
var $rows = $('tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
</script>
</head>
<body>
<span class="data-heading right">
Search:<input type="text" id="search" placeholder="Type to search">
</span>
<table id="table"></table>
</body>
</html>

Answer

Add $(document).ready(function() instead of onload

$(document).ready(function() {
var table = document.getElementById("table");

table.innerHTML = "";
for (var i = 0; i < 6; i++) {
  var js = "apple";
  var tr = document.createElement("tr");
  var td = document.createElement("td");

  td.innerHTML = js + i ;
  tr.appendChild(td);
  table.appendChild(tr);
}


var $rows = $('tr');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});
});
Comments