Search code examples
javascriptphphtmlsmarty

Search for javascript in html does not work


I want to display the search in the site header in the tpl file


<div  class="search-widget" >

<form method="get" action="art/search">

<input type="text"  id="artnum" value="" maxlength="40" placeholder="" > 


<button type="submit"  onclick="TDMArtSearch()">
<i class="material-icons search">&#xE8B6;</i>
 <span class="hidden-xl-down"></span>
        </button>
</form>
<div class="tclear"></div>

<script type="text/javascript">

function TDMArtSearch(){
    var art = $('#artnum').val();
    if(art!=''){
        art = art.replace(/[^a-zA-Z0-9.-]+/g, '');
        location = '/art/search/'+art+'/';
    }
}
$('#artnum').keypress(function (e){
  if(e.which == 13){ TDMArtSearch(); return false;}
});
</script

        ></button>
    </form>
</div>

Search does not work. If I delete form method="get" action="art/search". Then search works. Only works if you click on the search button. How to apply the form method to start searching with the enter key


Solution

  • Just make the form executes the javascript function on submit:

    <div  class="search-widget" >
    
    <form method="get" action="art/search" onsubmit="TDMArtSearch(); return false;">
    
    <input type="text"  id="artnum" value="" maxlength="40" placeholder="" > 
    
    <button type="submit"  onclick="TDMArtSearch()">
    <i class="material-icons search">&#xE8B6;</i>
     <span class="hidden-xl-down"></span>
            </button>
    </form>
    <div class="tclear"></div>
    
    <script type="text/javascript">
    
    function TDMArtSearch(){
        var art = $('#artnum').val();
        if(art!=''){
            art = art.replace(/[^a-zA-Z0-9.-]+/g, '');
            location = '/art/search/'+art+'/';
        }
    }
    </script
    
            ></button>
        </form>
    </div>
    

    onsubmit attribute is to execute javascript when form is submited and return false is to stop "normal" submission. There are better ways to do this by adding listeners and having cleaner HTML code, but you can look for that once you know how this works.