1

Im having the following Function where user hits inputs new Key, the save into the DB., but the problem is im input are getting saved into db as 1,12,123,124,1245,12456...and so on? how can i input the value as a whole. ?

 wo_input.oninput = function() {
            if (wo_input.value) {
                if (wo_input.value.length > 0) {
                    saveOnChange(wo_input.value, 'wo_number');
                } else { }
            } else { }
        }  

Save on Change Function

function saveOnChange(val, type) {
    var diagnosis_id = $('#diagnosis_id').val();
    console.log(val + " : " + type + " : " + diagnosis_id);
    $.post('/diagnosis/saveOnChange', {
        '_token': '{{ csrf_token() }}',
        'diagnosis_id': diagnosis_id,
        'value': val,
        'type': type
    }, function(success) {
        console.log(success);
        if (success.redirect) {
            //window.location.href = '/diagnosis/edit/' + success.id;
            window.history.pushState('edit', 'Title', '/diagnosis/edit/'+success.id);
        }
    });
}

HTML

<input class="saveonchange add_media id_input" type="text" name="wo_number" value="" id="wo_input"/>
Bal Sankar
  • 17
  • 1
  • 5

2 Answers2

0

If I understand you right, you want to save the whole value once the user finished typing, and not every time the user presses a key.

You could use jQuery's change event:
https://www.w3schools.com/jquery/event_change.asp

Inputs also have a blur event you may check out:
https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event

IamFlok
  • 64
  • 4
  • Yes, `onchange` Works but this has to feel dynamic, so that value will be saved after like 5 secs after no typing. – Bal Sankar Sep 09 '20 at 14:05
0

You can use setTimeout() to check after a certain delay if there where no changes after that delay. If there where none then save it to your database.

Using new Date().getTime() you get the amount of milliseconds since 1970/01/01 which you can use for your check.

Below example logs a console message when there was no input for 2 seconds.

const ms = 2000;

$('#test').on('input', (e) => {
  $(e.currentTarget).data('updated', new Date().getTime());
  setTimeout(() => { 
    if(new Date().getTime() - ms >= $(e.currentTarget).data('updated')) {
      console.log(`${ms}ms past. Go save!`);
    }
  }, ms);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test">
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73