Home > Mobile >  Is there a way to automatically submit a form after text is populated via $_GET?
Is there a way to automatically submit a form after text is populated via $_GET?

Time:11-06

I am bringing a value to a page via $_GET and inserting it into my search textbox. The box is an auto complete using ajax. The problem is that when it is dropped into the search box it doesn't auto search. It needs me to press a key to fire off. Is there an easy way to get it to submit after the value is inserted? Or maybe a different method for accomplishing this?

<div class="form-group">
    <input type="text" name="search_box" id="search_box" class="form-control input-lg" placeholder="Type your search here" '.(isset($_GET['search']) ? 'value="'.$_GET['search'].'"' : "").' />
</div>
<script>
  $(document).ready(function(){

    load_data(1);

    function load_data(page, query = '')
    {
      $.ajax({
        url:"fetch.php",
        method:"POST",
        data:{page:page, query:query},
        success:function(data)
        {
          $('#dynamic_content').html(data);
        }
      });
    }

    $(document).on('click', '.page-link', function(){
      var page = $(this).data('page_number');
      var query = $('#search_box').val();
      load_data(page, query);
    });

    $('#search_box').keyup(function(){
      var query = $('#search_box').val();
      load_data(1, query);
    });

  });
</script>

CodePudding user response:

Well since you are using jQuery it is as simple as triggering the event

var search = $('#search_box');
search.keyup(function(){ .... });
if (search.val().trim()) search.trigger('keyup');

or just call your function

var searchValue = $('#search_box').val().trim();
if (searchValue) load_data(1, searchValue);

CodePudding user response:

u can try to emulate the "enter"

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

Demo

  • Related