There was such a problem. There is an input field

<input type="number" onblur="func()" /> 

When this field loses focus, the js (func) function is executed. In this script, data is sent to the server, where the data is stored in the database. Everything works as it should, but if the user entered data into this input and closed the browser or tab, the data does not go to the server. How to be? How to fix it?

  • can add a submit button? - Horchynskyi
  • I have a table of these inputs 30 * 30. On the server, it is easier to add one by one incoming input, rather than immediately across the entire heap. - NoName

2 answers 2

You can use another event, for example oninput , although in this case any change in value will be sent to the server immediately

 function func() { var num = document.getElementsByTagName('input')[0]; console.log('sending changed value to server (value = ' + num.value + ')') }; 
 <input type="number" oninput="func()" /> 

  • and with each change will there be a change in the database? that is, for example, if I enter a line there, well, let's say of 10 characters, then this record will be updated 10 times for each character in the database? In my opinion, this is not good. - NoName
  • @NoName, you can still try to play with the beforeunload event, so that when you try to close, the browser asks if you are sure that you want to close because data can be lost and razvedyvat already on the yuzver - Rostyslav Kuzmovych
  • So I think so. The object’s focus will be lost if a message pops up. So in any case, the data will go away - NoName

 var input = document.getElementById('foo'); input.addEventListener("focusout", function() { console.log('Sending data to server...'); }); 
 <input type="number" id="foo" />