Getting searchfield in focus and activating Return key as search trigger

Hi,

I have this page http://kroweb.dk/gfdev/godser/godser.php

Everything is working nicely except for two things.

I would like to get the searchfield in focus when the page opens or is refreshed  - searchfield id is "input_1"

I need to get the Return key to perform the search as well as the Search button does. The search button ("Søg") works nicely, but the Return key return nothing and it seems thar it is actually resetting the page.

Hoping that somebody can guide me in the right direction I paste in a little code here below.

I have this form:
<form action=""  id="search2" form title="Skriv evt. bare en del af det sted du søger, eller brug % som jokertegn når du søger bredt. Hvis du søger eksakt skal du skrive det eksakte navn på det du søger" style="padding-top:10px; padding-bottom:10px;" method="POST" >

         <input type="search" id="input_1" placeholder= "Søg" style="width: 300px; height: 35px; border: 1px solid #666666;border-radius:2px;color:#666666; color: #9F5584; font-weight: ligther; font-size: 13px; padding-left:10px;" name="query"  />

         <input type="button" submit title="Klik her, eller tast Enter, for at aktivere søgningen." style="margin-left:15px; padding-right:10px;height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" name="soeg" id="Sog" value="Søg"/>


         <input type="submit" id="nulstil" style="margin-left:15px; height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" value="Nulstil"/>
       </form>  

Open in new window


and I have these functions to activate the search button and the Return key:
     // "Søg" button function
      SogButton.addEventListener('click',function (){
        $('#list_items > table').remove();    
        $.ajax({
         url: radioBtn(),
         data: {query:input_1.value},
         method:'POST',
         dataType: 'html'
       }).done(function (res){             
        $('#list_items').html(res);
        $('#tdata').DataTable({searching: true, paging: false, info: true, "dom": '<"top"<if>', order: []});
        
      });         

     });


        // Return key search function
        input_1.addEventListener('keyup',function(e){
          if(e.keyCode===13 ){            
           $.ajax({
             url: radioBtn(),
             data: {query:input_1.value},
             method:'POST',
             dataType: 'html'
           }).done(function (res){
            $('#list_items').html(res);
            $('#tdata').DataTable({searching: true, paging: false, info: true, "dom": '<"top"<if>', order: []});
            
          });
         }
       }); 

Open in new window

Peter KromanSenior Proposal SpecialistAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongCommented:
I would like to get the searchfield in focus when the page opens or is refreshed  - searchfield id is "input_1"

try add:

$(document).ready(function(){ 
    $("#input_1").focus(); 
});

Open in new window


The search button ("Søg") works nicely, but the Return key return nothing and it seems thar it is actually resetting the page.

try change:

<input type="submit" id="nulstil" style="margin-left:15px; height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" value="Nulstil"/>

Open in new window


to:
<input type="button" id="nulstil" style="margin-left:15px; height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" value="Nulstil"/>

Open in new window

0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Thanks Ryan,

I have tested both your suggestions. Sadly none of them are working.
0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Sorry Ryan - the focus function works now - my fault.

But the Return key does not work yet.
But you have adressed the Reset button regarding this - is that correct?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Peter KromanSenior Proposal SpecialistAuthor Commented:
A little addition.
Sometimes when hitting the Enter key after having put in a search text - not every time - it looks like it is presenting the table, but imediately it dissapears again and the page resets.
0
leakim971PluritechnicianCommented:
check lines 84 to 86, use line 85 or 86 (86 need to be uncommented of course)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .coolSearchTextbox {
            width: 300px;
            height: 35px;
            border: 1px solid #666666;
            border-radius:2px;
            color:#666666;
            color: #9F5584;
            font-weight: ligther;
            font-size: 13px;
            padding-left:10px;
        }
        .coolButton {
            margin-left:15px;
            padding-right:10px;
            height:30px;
            font-family:arial;
            font-size: 12px;
            text-align:left;
            background-color:#cccccc;
            border: 2px solid #grey;
            border-radius:2px;
            color:black;
            background-color:#cccccc;
            box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
        }
        .coolSubmitButton {
            margin-left:15px;
            height:30px;font-family:arial;
            font-size: 12px;
            text-align:left;
            background-color:#cccccc;
            border: 2px solid #grey;
            border-radius:2px;
            color:black;
            background-color:#cccccc;
            box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
        }
        .coolForm {
            padding-top:10px;
            padding-bottom:10px;
        }
    </style>
    <script>


        jQuery(function($) {

            function radioBtn() {
                var url = "/path/to/ajax";
                return url;
            }

            // "Søg" button function
            var postWithAjax = function() {
                $.ajax({
                    url: radioBtn(),
                    data: { query: $("#input_1").val() },
                    method:'POST',
                    dataType: 'html'
                }).done(function (res){
                    $('#list_items').html(res);
                    $('#tdata').DataTable({searching: true, paging: false, info: true, "dom": '<"top"<if>', order: []});

                });
            }

            $("#Sog").click(function (){
                $('#list_items > table').remove();
                postWithAjax();
            });

            // Return key search function
            $("#input_1").keyup(function(e){
                if(e.which===13 )
                    postWithAjax();
            });

            $("#input_1").focus();
            $("#Sog").click(); // or just REPLACE this line by the following line by uncommenting her
            // postWithAjax();
        });

    </script>
</head>
<body>
<form action="" id="search2" class="coolForm" form title="Skriv evt. bare en del af det sted du søger, eller brug % som jokertegn når du søger bredt. Hvis du søger eksakt skal du skrive det eksakte navn på det du søger" method="POST" >
    <input type="search" id="input_1" name="query" class="coolSearchTextbox" placeholder= "Søg"  />
    <input type="button" id="Sog" name="soeg" class="coolButton" value="Søg" title="Klik her, eller tast Enter, for at aktivere søgningen." submit/>
    <input type="submit" id="nulstil" class="coolSubmitButton" value="Nulstil"/>
</form>
</body>
</html>

Open in new window

0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Thanks leakim971,

I have tried your suggestion (all of the script). It gives exactly the (missing) same functionality as before.
0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Hi,

I simply don't understand why the Enter key is performing a reset of the page when pressed when the search field is in focus.
I have a similar setup functioning on several other pages.
Hope that somebody can help me put this puzzle together an I paste in the total code for the page here:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

<!DOCTYPE html>
<html lang="da">
<head>
  <!-- Check for title--> 
  <title>Godser</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="style_godser.css" />
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css" />

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
   <script type="text/javascript" src="https://cdn.datatables.net/select/1.2.4/js/dataTables.select.min.js"></script>
  
</head>


<body>
 
  <!-- Page content start-->        
  <div class="w3-row">

 
    <!-- Main page start -->  

    <div class="w3-row">

      <!-- Column1 start-->         
      <div class="w3-col w3-mobile" style="width:65%; margin-top: 30px; margin-left: 20px; margin-bottom:10px; margin-right: 8px; padding-bottom: 10px;">

 
        <!-- Valgknapper til bred/eksakt søgning -->

        <form style="color:#9F5584; padding-bottom:7px;"> 

          <input type="radio" id="broad" style="position:relative; margin-left: 0px; background-color: #eee;" checked="checked" name="radio1" value="bredt" /> Søg bredt 
          <input type="radio" id="exact" style="position: relative;" name="radio1" value="eksakt"/> Søg eksakt Sogn
         <input type="radio" id="exacts" style="position: relative;" name="radio1" value="eksakts"/> Søg eksakt Gods

        </form> 


        <!-- Søge felt til steder -->
        <form action=""  id="search2" form title="Skriv evt. bare en del af det sted du søger, eller brug % som jokertegn når du søger bredt. Hvis du søger eksakt skal du skrive det eksakte navn på det du søger" style="padding-top:10px; padding-bottom:10px;" method="POST" >

         <input type="search" id="input_1" placeholder= "Søg" style="width: 300px; height: 35px; border: 1px solid #666666;border-radius:2px;color:#666666; color: #9F5584; font-weight: ligther; font-size: 13px; padding-left:10px;" name="query"  />

         <input type="button" submit title="Klik her, eller tast Enter, for at aktivere søgningen." style="margin-left:15px; padding-right:10px;height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" name="soeg" id="Sog" value="Søg"/>


         <input type="reset" id="nulstil" style="margin-left:15px; height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" value="Nulstil"/>
       </form>  
       

       <div id="list_items" class ='list'></div>

        <script>
        //Variable to be used in the scripts
      var input_1 = document.getElementById('input_1'); //main searchfield
      var SogButton=document.getElementById('Sog'); //"Søg" buttin
      var NustilButton=document.getElementById('nulstil');  //"Nulstil" button 
      
      $(document).ready(function(){ 
        $("#input_1").focus(); 
      });


        function radioBtn(){
         var linkPhp;
         if($("#broad").is(":checked")) {
           linkPhp='ajaxListHtml.php';        
           return linkPhp;
         }else if($("#exact").is(":checked")){
           linkPhp='ajaxListHtml2.php';         
           return linkPhp;  
         }else{        
          linkPhp='ajaxListHtml3.php';         
          return linkPhp;  }
        }    


      // "Søg" button function
      SogButton.addEventListener('click',function (){
        $('#list_items > table').remove();    
        $.ajax({
         url: radioBtn(),
         data: {query:input_1.value},
         method:'POST',
         dataType: 'html'
       }).done(function (res){             
        $('#list_items').html(res);
        $('#tdata').DataTable({responsive: true, searching: true, paging: false, info: true, select: true, "dom": '<"top"if>t', order: []});
        
      });         

     });


        // Return key search function
        input_1.addEventListener('keyup',function(e){
          if(e.keyCode===13 ){            
           $.ajax({
             url: radioBtn(),
             data: {query:input_1.value},
             method:'POST',
             dataType: 'html'
           }).done(function (res){
            $('#list_items').html(res);
            $('#tdata').DataTable({responsive: true, searching: true, paging: false, info: true, select: true, "dom": '<"top"if>t', order: []});
            
          });
         }
       }); 
  

        //"Nulstil" button
      NustilButton.addEventListener('click',function (){
        document.getElementById("exact").checked = false;
        document.getElementById("broad").checked = true;
        $('#list_items > table').remove();
        $(document).ready(function(){ 
        $("#input_1").focus(); 
      });

          });       
      
     </script>



       <div class="w3-row" style="width:100%;">         
        <br> 
        <hr style= "margin-left: 10px; width: 95%;  border-color: #9F5584;">   
      </div>    


<!-- Column1 end--> 


</div>
<!-- Main page end--> 

</div>  
</div>
<!-- Page content end-->  

</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
leakim971PluritechnicianCommented:
let say when you press enter, you run the ajax to do the search right ?
why not just calling the ajax at page load, let me know (line 86)
0
Ryan ChongCommented:
you got two forms in your page and it's a bad design to handle a single operation. you should combine them into just one form.

<form style="color:#9F5584; padding-bottom:7px;"> 

Open in new window


<form action=""  id="search2" form title="Skriv evt. bare en del af det sted du søger, eller brug % som jokertegn når du søger bredt. Hvis du søger eksakt skal du skrive det eksakte navn på det du søger" style="padding-top:10px; padding-bottom:10px;" method="POST" >

Open in new window

0
Ryan ChongCommented:
you probably can try something like this:

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

<!DOCTYPE html>
<html lang="da">
<head>
  <!-- Check for title--> 
  <title>Godser</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="style_godser.css" />
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css" />

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
   <script type="text/javascript" src="https://cdn.datatables.net/select/1.2.4/js/dataTables.select.min.js"></script>
  
</head>


<body>
 
  <!-- Page content start-->        
  <div class="w3-row">

 
    <!-- Main page start -->  

    <div class="w3-row">

      <!-- Column1 start-->         
      <div class="w3-col w3-mobile" style="width:65%; margin-top: 30px; margin-left: 20px; margin-bottom:10px; margin-right: 8px; padding-bottom: 10px;">

 
        <!-- Valgknapper til bred/eksakt søgning -->

        <form action=""  id="search2" title="Skriv evt. bare en del af det sted du søger, eller brug % som jokertegn når du søger bredt. Hvis du søger eksakt skal du skrive det eksakte navn på det du søger" style="padding-top:10px; padding-bottom:10px;color:#9F5584; padding-bottom:7px;" method="POST" >

          <input type="radio" id="broad" style="position:relative; margin-left: 0px; background-color: #eee;" checked="checked" name="radio1" value="bredt" /> Søg bredt 
          <input type="radio" id="exact" style="position: relative;" name="radio1" value="eksakt"/> Søg eksakt Sogn
         <input type="radio" id="exacts" style="position: relative;" name="radio1" value="eksakts"/> Søg eksakt Gods<br />
&nbsp;<!-- Søge felt til steder --><input type="search" id="input_1" placeholder= "Søg" style="width: 300px; height: 35px; border: 1px solid #666666;border-radius:2px;color:#666666; color: #9F5584; font-weight: ligther; font-size: 13px; padding-left:10px;" name="query"  />

         <input type="submit" title="Klik her, eller tast Enter, for at aktivere søgningen." style="margin-left:15px; padding-right:10px;height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" name="soeg" id="Sog" value="Søg"/>
        <input type="reset" id="nulstil" style="margin-left:15px; height:30px;font-family:arial; font-size: 12px; text-align:left; background-color:#cccccc; border: 2px solid #grey;border-radius:2px; color:black; background-color:#cccccc; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);" value="Nulstil"/>
       </form>  
       

       <div id="list_items" class ='list'></div>

        <script>
            //Variable to be used in the scripts
            var input_1 = document.getElementById('input_1'); //main searchfield
            var SogButton = document.getElementById('Sog'); //"Søg" buttin
            var NustilButton = document.getElementById('nulstil');  //"Nulstil" button 

            $(document).ready(function () {
                $("#input_1").focus();
            });


            function radioBtn() {
                var linkPhp;
                if ($("#broad").is(":checked")) {
                    linkPhp = 'ajaxListHtml.php';
                    return linkPhp;
                } else if ($("#exact").is(":checked")) {
                    linkPhp = 'ajaxListHtml2.php';
                    return linkPhp;
                } else {
                    linkPhp = 'ajaxListHtml3.php';
                    return linkPhp;
                }
            }

            $("#search2").submit(function (event) {
                $('#list_items').html("");
                //$('#list_items > table').remove();
                $.ajax({
                    url: radioBtn(),
                    data: { query: input_1.value },
                    method: 'POST',
                    dataType: 'html'
                }).done(function (res) {
                    $('#list_items').html(res);
                    $('#tdata').DataTable({ responsive: true, searching: true, paging: false, info: true, select: true, "dom": '<"top"if>t', order: [] });

                });
                event.preventDefault();
            });


            //"Nulstil" button
            NustilButton.addEventListener('click', function () {
                document.getElementById("exact").checked = false;
                document.getElementById("broad").checked = true;
                $('#list_items').html("");
                //$('#list_items > table').remove();
                $(document).ready(function () {
                    $("#input_1").focus();
                });
            });

     </script>



       <div class="w3-row" style="width:100%;">         
        <br> 
        <hr style= "margin-left: 10px; width: 95%;  border-color: #9F5584;">   
      </div>    


<!-- Column1 end--> 


</div>
<!-- Main page end--> 

</div>  
</div>
<!-- Page content end-->  

</html>

Open in new window

0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Hi leakim971,

Because there were no actual solution to this specific question, and I have got it solved in another way.

Hope that is explanation enough?
0
Ryan ChongCommented:
@Peter
have you tried my last suggestion in ID: 42434444?
0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Yes Ryan,

I have tried it, but as I've described above here, I have got the problem solved otherwise.
Thanks for the contribution anyway :)
0
Peter KromanSenior Proposal SpecialistAuthor Commented:
Problem is solved elsewhere
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.