0

I would like to on the reload of my page, set my value search (stock in localStorage) in an input and after that simulate a keypress (type 13).

Here is my code :

$( function () {

if( (localStorage.getItem("search")) &&  (sessionStorage.getItem("reloadAfterPageLoad")!="false") )   
{
   $('#datatable_filter  input').val(localStorage.getItem("search")).focus().trigger(jQuery.Event('keypress', { keycode: 13, which: 13,  charCode: 13 }));


} 
});

The focus() works as the localStorage.getItem("search") but my event never happens.

I already try the solution of Definitive way to trigger keypress events with jQuery :

$( function () {

if( (localStorage.getItem("search")) &&  (sessionStorage.getItem("reloadAfterPageLoad")!="false") )   
{
var e = jQuery.Event("keypress");
e.which = 13;
alert( "la recherche était : "+localStorage.getItem("search"));
$('#datatable_filter  input').val(localStorage.getItem("search")).focus().trigger(e);
sessionStorage.setItem("reloadAfterPageLoad", "false");

} 

And it also don't works.

Any idea about the problem ? Thanks in advance for you help

  • And by triggering the `keypress` like that, what is supposed to happen, should a form submit or what ? – adeneo Aug 08 '17 at 16:16
  • Possible duplicate of [Definitive way to trigger keypress events with jQuery](https://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery) – user1777136 Aug 08 '17 at 17:04
  • @ adeneo21 : a table should be refresh as search will apply a filter on my data – anneso bada Aug 09 '17 at 13:52
  • What are you trying to achieve after keypress? If there is a listener for keypress then move the logic written in the listener to a function, by this you can call that function instead of making a key trigger – Jibin.Jay Aug 09 '17 at 14:21
  • @Jibin.Jay : I have a input with a listener that filter my data in a table. On change and when you press enter in this input the table is uptaded according the value of the search. On window loading, I succeed to be in the input with the previous value I searched and I want to simulate a press of "enter" to activate my listener and update my table – anneso bada Aug 09 '17 at 14:50

1 Answers1

0

You can move your input's keyenter/change logic to another function and call it.

$('input').keypress(function(event) {
  updateTable(event);
});

function updateTable(event) {
  //update the table
}

#onLoad
$(function() {
  if ((localStorage.getItem("search")) && (sessionStorage.getItem("reloadAfterPageLoad") != "false")) {
    $('#datatable_filter  input').val(localStorage.getItem("search")).focus();
    updateTable();
  }
});
Jibin.Jay
  • 332
  • 1
  • 5