Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>Search</title>
- <style>
- /*
- Allow CSS to perform the necessary style
- changes to elected DOM elements rather
- than use JS to do trivial tasks.
- */
- body *{font-family:monospace}
- .bordered{border:1px solid #A5ACB2;}
- td,th{border:1px solid rgba(0,0,0,0.25);padding:0.1rem;}
- tr{background:rgb(230, 240, 255)}
- tr:hover{background:rgb(0, 90, 20);cursor:pointer;color:white}
- td:hover{background:yellowgreen}
- th{background:darkgray;color:white}
- </style>
- </head>
- <body>
- <form name='search'>
- <label>Country: <input type='text' name='query' size='30' /></label>
- <div id='livesearch'></div>
- </form>
- <script>
- const div=document.getElementById('livesearch');
- const cn='bordered';
- document.forms.search.query.addEventListener('keyup',function(e){
- if( this.value=='' ){
- div.innerHTML='';
- div.classList.remove(cn)
- }else{
- // clear the display before adding NEW content.
- div.innerHTML='';
- fetch( 'searchCountry.php?q='+this.value )
- .then( r=>r.text() )
- .then( text=>{
- // this is the ajax callback. Add the generated content to specified parent
- // and allow event delegation to process any events registered.
- // use this to process the response however you see fit!
- div.insertAdjacentHTML('afterbegin',text);
- div.classList.add(cn)
- })
- }
- });
- /*******************************
- Delegated Event listener
- ------------------------
- Note that this is "bound" to the DIV that will accept the
- new HTML content in the ajax callback
- */
- div.addEventListener('click',function(e){
- if( e.target!=e.currentTarget && e.target.tagName=='TD' ){
- console.log( 'Do something with: %s?', e.target.textContent )
- }
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement